Skip to content
Advertisement

how can i add key value pair in array inside another array

// I have the following response :

    [
  {
    "userId": 1,
    "id": 3,
    "title": "fugiat veniam minus",

"company": {
      "name": "Deckow-Crist",
      "catchPhrase": "Proactive didactic contingency",
      "bs": "synergize scalable supply-chains"
    }
  },


 {
    "userId": 2,
    "id": 4,
    "title": "fugiat veniam minus",

"company": {
      "name": "Deckow-Crist",
      "catchPhrase": "Proactive didactic contingency",
      "bs": "synergize scalable supply-chains"
    }
  },

 ]

//and I want to add this key-value pair in 2 places (“completed”: false) to make it look like the following response:

[
  {
    "userId": 1,
    "id": 3,
    "title": "fugiat veniam minus",
     **"completed": false**

"company": {
      "name": "Deckow-Crist",
      "catchPhrase": "Proactive didactic contingency",
      "bs": "synergize scalable supply-chains"
       **"completed": false**
    }
  },


 {
    "userId": 2,
    "id": 4,
    "title": "fugiat veniam minus",
     **"completed": false**
     "company": {
      "name": "Deckow-Crist",
      "catchPhrase": "Proactive didactic contingency",
      "bs": "synergize scalable supply-chains"
     **"completed": false**
    }
  },  
  
]

………………………………………………………………………………………………………..

Advertisement

Answer

Array.map can solve your problem.

const result = input.map(x => {
    x.completed = false;
    x.company = x.company.map(c => ({ ...c, completed: false }))
    return x;
})

You can check the completed demo:

const input = [{
    "userId": 1,
    "id": 3,
    "title": "fugiat veniam minus",
    "company": [{
      "name": "Deckow-Crist",
      "catchPhrase": "Proactive didactic contingency",
      "bs": "synergize scalable supply-chains"
    }, {
      "name": "Deckow-Crist",
      "catchPhrase": "Proactive didactic contingency",
      "bs": "synergize scalable supply-chains"
    }]
  },
  {
    "userId": 2,
    "id": 4,
    "title": "fugiat veniam minus",
    "company": [{
      "name": "Deckow-Crist",
      "catchPhrase": "Proactive didactic contingency",
      "bs": "synergize scalable supply-chains"
    }, {
      "name": "Deckow-Crist",
      "catchPhrase": "Proactive didactic contingency",
      "bs": "synergize scalable supply-chains"
    }]
  },
];

const result = input.map(x => {
  x.completed = false;
  x.company = x.company.map(c => ({ ...c, completed: false }))
  return x;
})

console.log(result);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement