1
const data = [
 {name:'Apple', order:1, path:'0'}
 {name: 'Orange', order:2, path:'1'}
 {name: 'Banana', order:3, path:'2'}
 {name: 'Grape', order:4, path:'3'}
]

const newObj = {name: 'Mango', order:3, path:'2'}

I want to insert the new object data in the 'data' array in between the 'Orange' - 'Banana' and also change the order values and path values based on the new object order and path value.

I mean based on the new object path and order value the new object will insert the correct position.

the answer is like below:-

const data = [
 {name:'Apple', order:1, path:'0'}
 {name: 'Orange', order:2, path:'1'}
 {name: 'Mango', order:3, path:'2'}
 {name: 'Banana', order:4, path:'3'}
 {name: 'Grape', order:5, path:'4'}
]

I tried this solution but I want to increase my object order and path count.

imjayabal
  • 805
  • 1
  • 12
  • 24

1 Answers1

1

You can insert an object using Array.prototype.slice and then update each item by using a for loop to update only the elements after the insert (since only those elements' order will change):

const data = [
 {name:'Apple', order:1, path:'0'},
 {name: 'Orange', order:2, path:'1'},
 {name: 'Banana', order:3, path:'2'},
 {name: 'Grape', order:4, path:'3'}
];
const newObj = {name: 'Mango', order:3, path:'2'}

data.splice(newObj.path, 0, newObj);
for (let i = newObj.order; i < data.length; i++) { // update order of elements after inserted element
    data[i].order += 1; // update order
    data[i].path = `${i}`; // update path
}
console.log(data);
awarrier99
  • 3,628
  • 1
  • 12
  • 19
  • @imjayabal I added an edit to incorporate the `path` change as well – awarrier99 May 10 '20 at 03:56
  • @imjayabal Also, you can use `map` or `forEach` like you suggested in your edit, which I had actually originally done, but there's no need to iterate over the elements before the inserted item, since their order and path won't change, so I did it like this to make it a bit faster in case it's a large array – awarrier99 May 10 '20 at 03:58