Home > Software design >  Javascript conditionally adding the nested object using map() operator
Javascript conditionally adding the nested object using map() operator

Time:09-27

I have a below JSON,

var original =  {
  "todos": [
    {
      "accountNo": "50190000",
      "name": "Sarkar",
      "vpainfo": [
        {
          "vpa": "log@bda",
          "mccCode": "0000"
        }
      ]
    }
  ]
}

And am trying to add new data inside the nested array i.e., "vpainfo". I have tried using the below code and able to adding the new values inside "vpainfo".

var newdata = {"vpa":"first@bda","mccCode":"1111"};


var newObj = 
    Object.assign({}, original,
    {
      todos: original.todos.map(todoInfo=>(todoInfo.accountNo=="50190000")?[
        ...todoInfo.vpainfo,
        newdata
      ]: todoInfo)
    });

And the resulted object is,

{"todos":[[{"vpa":"log@bda","mccCode":"0000"},{"vpa":"first@bda","mccCode":"1111"}]]}

But few of the key and values(accountNo and name) are getting missed, how do we get the full object with the latest updated values?

CodePudding user response:

You only return the array, not the actual object, hence the error.

var original =  {
  "todos": [
{
  "accountNo": "50190000",
  "name": "Sarkar",
  "vpainfo": [
    {
      "vpa": "log@bda",
      "mccCode": "0000"
    }
  ]
}
  ]
}

const newdata = {"vpa":"first@bda","mccCode":"1111"};


const newObj = Object.assign({}, original,
    {
      todos: original.todos.map(todoInfo=>{
         if(todoInfo.accountNo=="50190000"){
           return {
              ...todoInfo, 
              vpainfo: [...todoInfo.vpainfo, newdata]
              }
          }
       return todoInfo
      })
    });

console.log(newObj)

CodePudding user response:

All those spread operators seem a little excessive...

If all you wanna do is add newdata to that existing array, then do that:

var original = {
  "todos": [{
    "accountNo": "50190000",
    "name": "Sarkar",
    "vpainfo": [{
      "vpa": "log@bda",
      "mccCode": "0000"
    }]
  }]
};

const newdata = {
  "vpa": "first@bda",
  "mccCode": "1111"
};

// Find the correct account.
const account = original.todos.filter(t => t.accountNo === '50190000')[0];
if (account) {
  account.vpainfo.push(newdata);
}

console.log(original);

  • Related