Skip to content
Advertisement

How to push an object into an array nested in an array of objects?

So I have this arr

let arr = [{
 category_set_id: 25,
 name: "25name",
 el: [
   {name: "25name1", value: "25value1"}
 ]
},
{
 category_set_id: 44,
 name: "44name",
 el: [
   {name: "44name1", value: "44value1"}
 ]
},
]

And this is the element i need to push into this arr of objects

let elToPush = {category_set_id: 44, name: "44name2", value: "44value2"}

As you can see, it belongs in the second eleement of the arr, and it must somehow be pushed into the el property, resulting in

let arr = [{
 category_set_id: 25,
 name: "25name",
 el: [
   {name: "25name1", value: "25value1"}
 ]
},
{
 category_set_id: 44,
 name: "44name",
 el: [
   {name: "44name1", value: "44value1"},
   {name: "44name2", value: "44value2"}
 ]
},
]

So I know I can maybe first filter the arr to get my desired section, fe

let toModify = arr.filter(i => i.category_set_id === elToPush.id)

Then having that I could

let newarr = [toModify.el, ...elToPush]
toModify.el = newarr

And finally I must somehow replace it in the global arr

Can someone lend a hand with this?

Advertisement

Answer

You can use findIndex to find the index of category_set_id: 44, from arr. If arr contains such object then it will return the index which will be greater than -1. Then use this index to push the required value

let arr = [{
    category_set_id: 25,
    name: "25name",
    el: [{
      name: "25name1",
      value: "25value1"
    }]
  },
  {
    category_set_id: 44,
    name: "44name",
    el: [{
      name: "44name1",
      value: "44value1"
    }]
  }
];

let elToPush = {
  category_set_id: 44,
  name: "44name2",
  value: "44value2"
};

const getIndex = arr.findIndex(item => item.category_set_id === elToPush.category_set_id);
if (getIndex > -1) {

  arr[getIndex].el.push({
    name: "44name2",
    value: "44value2"
  })

};

console.log(arr)

Alternatively you can also use find which will return the object if category_set_id matches

let arr = [{
    category_set_id: 25,
    name: "25name",
    el: [{
      name: "25name1",
      value: "25value1"
    }]
  },
  {
    category_set_id: 44,
    name: "44name",
    el: [{
      name: "44name1",
      value: "44value1"
    }]
  }
];

let elToPush = {
  category_set_id: 44,
  name: "44name2",
  value: "44value2"
};

const obj = arr.find(item => item.category_set_id === elToPush.category_set_id);
obj && obj.el.push({
  name: elToPush.name,
  value: elToPush.value
})
console.log(arr)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement