0

I have an array of object and an object for eg: arr=[{id:1,name:"foo"},{id:2,name:"bar"}] and my new object is obj={id:1,name:"baz"}.I want to replace the obj based on key inside an array. The expected out is output=[{id:1,name:"baz"},{id:2,name:"bar"}] I have done some work around like following:

function removeObjBasedID(arr, obj) {
  let newArr = [];

  arr.map((item, i) => {
    if (item.id == obj.id) {

      newArr.splice(i, 1);

    } else {
      newArr = [...arr, obj];

    }
  });

  return newArr;
}

console.log(removeObjBasedID(arr, obj));


i.signori
  • 585
  • 3
  • 16
Subee Na
  • 57
  • 6
  • does replace means mutating or do you want a new array? – Nina Scholz Nov 22 '19 at 09:00
  • `map` is **not** for looping through arrays. It's for *mapping* arrays. My answer [here](https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript/9329476#9329476) shows options for just looping (but in this case, you probably want `filter`). – T.J. Crowder Nov 22 '19 at 09:02
  • yes i want new array – Subee Na Nov 22 '19 at 09:06

5 Answers5

2

You could iterate the array and update if found, or push the object.

function update(array, object) {
    for (let i = 0; i < array.length; i++) {
        if (array[i].id !== object.id) continue;
        array[i] = object;
        return;
    }
    array.push(object);
}

var array = [{ id: 1, name: "foo" }, { id: 2, name: "bar" }],
    object = { id: 1, name: "baz" };
    
update(array, object);

console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

const arr = [{id:1,name:"foo"},{id:2,name:"bar"}];
const newObject = { id: 1, name: "baz" };
const replacedIndex = arr.findIndex((el) => el.id === newObject.id);
arr[replacedIndex] = newObject;
console.log(arr)

You can easily find the index of the object that you want to replace from the array and assign the new object to the index found.

Nicolae Maties
  • 2,476
  • 1
  • 16
  • 26
0

If you want to create a new array, use filter:

const newArr = arr.filter(item => item.id !== obj.id);

If you want to mutate the existing array, you can use findIndex to find the entry and then use splice:

const index = arr.findIndex(item => item.id == obj.id);
if (index !== -1) {
    arr.splice(index, 1);
}

Note that that assumes just a single entry matches. If there may be multiple matches, I'd just loop through the array backward:

for (let index = arr.length - 1; index >= 0; --index) {
    const item = arr[index];
    if (item.id == obj.id) {
        arr.splice(index, 1);
    }
}

Going backward is important because when you splice, you move the following entries forward one.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Here is my solution

const arr = [{ id: 1, name: "foo" }, { id: 2, name: "bar" }];
const obj = { id: 1, name: "baz" };

function removeObjBasedID(arr, obj) {
    for (let idx in arr) {
        if (arr[idx].id === obj.id) {
            arr.splice(idx, 1, obj);
            return arr;
        }
    }
}

console.log(removeObjBasedID(arr, obj));

It reserves the order of the original array.

TopW3
  • 1,477
  • 1
  • 8
  • 14
-1

If you don't care about the position, then using es6

let arr = [{ id: 1, name: "foo" }, { id: 2, name: "bar" }]
let obj = { id: 1, name: "baz" }

arr = [obj, ...arr.filter(i => i.id !== obj.id)]