How to add an object to an array inside another object

1

I have the following function that creates an object:

function createDebit(name, value, paymentDate){
    var debit = {"type": name,"value": value,"PaymentDate": paymentDate};
    return debit;
}

This object that it returns I will add. on another object with this function:

var newDebit = createDebit("GVT", "200.00", "10/10/2010");
addValue("Bradesco", "arrayDebits", newDebit);

function addValue(where, element, content){
    var execute;
    var local = localStorage.getItem(where);
    local = JSON.parse(local);
    var verifyType = "$.isArray(local."+element+")";
    // Verifica se o elemento do objeto destino é um array
    if(eval(verifyType)){
        // Caso seja, add o conteudo via push
        if(typeof(content) == "string"){
            execute = "local."+element+".push('"+content+"')";
        }else if(typeof(content) == "object"){
            execute = "local."+element+".push("+content+")";
        }
    }else{
        execute = "local."+element+"='"+content+"'";
    }
    console.log(execute);
    console.log("Execute now...");
    eval(execute);
    console.log("Done Execute");
    storage_save(where, local);
}

But it always gives error:

  

jQuery.Deferred exception: Unexpected identifier SyntaxError: Unexpected identifier

If I try to pass the object via STRING:

function createDebit(name, value, paymentDate){
    var debit = '{"type":' + name + ',"value": ' + value + ',"PaymentDate": ' + paymentDate + '}';
    return debit;
}

  

{"nameCategory": "Bradesco", "arrayDebits": ["{\" type \ ": \" GVT \ ", \" value \

How can I actually save the object inside the array that is inside another object?

    
asked by anonymous 01.05.2017 / 21:19

1 answer

1

Do not use eval for this case , it is dangerous. The localStorage is useful but can not be trusted, and using strings of localStorage in eval is bad practice.

You can do this, note how to use [] to accessing object properties dynamically :

function createDebit(name, value, paymentDate) {
  return {
    "type": name,
    "value": value,
    "PaymentDate": paymentDate
  };
}

function addValue(where, element, content) {
  var local = JSON.parse(localStorage.getItem(where));
  if (!local[element]) local[element] = content;
  else local[element].push(content);
  console.log("Done!");
  storage_save(where, local);
}

var newDebit = createDebit("GVT", "200.00", "10/10/2010");
addValue("Bradesco", "arrayDebits", newDebit);
    
01.05.2017 / 21:30