0

I'm writing a simple Vue app where an Array with Objects should be updated with an incoming object.

I start with this Object:

var arr = 
[
  {
    "mainId": 1,
    "parents": [
      {
        "parent": 1
      },
      {
        "parent": 2
      }
    ]
  },
  {
    "mainId": 2,
    "parents": [
      {
        "parent": 3
      }
    ]
  }
]

I want to Update the "parent" Array with the following Object:

var updateArray = {
  "mainId": 2,
  "parent": 9
}

var updatedArray = 
[
  {
    "mainId": 1,
    "parents": [
      {
        "parent": 1
      },
      {
        "parent": 2
      }
    ]
  },
  {
    "mainId": 2,
    "parents": [
      {
        "parent": 3
      },
      {
        "parent": 9 // <-------------
      }
    ]
  }
]

What is the best way to achieve this?

Chris
  • 137
  • 2
  • 9

3 Answers3

1

You can look for the object using Array.find and it will give you a reference to the object inside the array, so when you update that object, it will be updated inside the array :

var arr = [{
    mainId: 1,
    parent: [{
        parent: 1
      },
      {
        parent: 2
      }
    ]
  },
  {
    mainId: 2,
    parent: [{
      parent: 3
    }]
  }
];

var updateArray = {
  mainId: 2,
  parent: 9
};

var obj = arr.find(o => o.mainId === updateArray.mainId);
obj.parent.push({
  parent: updateArray.parent
})

console.log(arr);
Taki
  • 17,320
  • 4
  • 26
  • 47
0

You can use find() to get the appropriate item by its mainId identifier and then use push() to add another object:

const arr = 
[
  {
    "mainId": 1,
    "parent": [
      {
        "parent": 1
      },
      {
        "parent": 2
      }
    ]
  },
  {
    "mainId": 2,
    "parent": [
      {
        "parent": 3
      }
    ]
  }
]

const id = 2
const obj = arr.find(({mainId}) => mainId === id)
obj.parent.push({ "parent": 9 })
console.log(arr)
zb22
  • 3,126
  • 3
  • 19
  • 34
0

You can achieve it by using native map function without any mutations:

const updatedArray = arr.map(obj => {
  if (obj.mainId === givenMainId) {
    const parent = obj.parent || []
    return { ...obj, parent: [...parent, { parent: givenParentId }] };
  }
  return obj;
})
Muhammad Ali
  • 2,538
  • 2
  • 16
  • 21