-2

I can go with find for editing one property like in this example. But I didn't find a syntax to edit more than one property.

const arr = [
  {
    id: 101,
    name: “Jone”,
    age: 1
  },
  {
    id: 102,
    name: “Jane”,
    age: 2
  },
  {
    id: 103,
    name: “johnny”,
    age: 3
  }
];
console.log(arr);
arr.find(element => element.id == 101).name = “jimmy”
console.log(arr);

2 Answers2

1

You can store the object that find returns and edit it as you need.

const arr = [
  {
    id: 101,
    name: 'Jone',
    age: 1
  },
  {
    id: 102,
    name: 'Jane',
    age: 2
  },
  {
    id: 103,
    name: 'johnny',
    age: 3
  }
];
console.log(arr);

// ****
const found = arr.find(element => element.id == 101)
found.name = 'jimmy'
found.age = 54
// ****

console.log(arr);
perepm
  • 940
  • 9
  • 22
  • In this way, the name of the object with id = 101 will still be jimmy, by assigning the value to a variable you exit the array and the edit will apply on the variable not the array. – George Saad Nov 02 '21 at 16:41
  • 1
    That's not true. Objects are passed by reference (most of the time). I strongly recommend that you check out [this answer](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) in stack overflow that explains it, and that you research a little bit more about the subject :) – perepm Nov 02 '21 at 16:48
  • I copy pasted from the question. [Here](https://www.typescriptlang.org/play?#code/MYewdgzgLgBAhgJwTAvDA2gKBjA3tnGASwBMAuGARgAZKAaAnMOAWwFMKAiAKXDc4aF4Acw5UCAX0F5GxclWoAmaU1ZiecMPxUixiydPxDSFGgGYdzdlwBWIABZgwATwGy4oimcmYAugG5MUEgQABs2ADpQkGEACkQEAEpAzAB6VJgAKmzMoPBoGAAzEABXMBJUeCQIwqJy2LZw9jBYFAA+GEa2ZqgI0lQ0GkpEzGKykgirNkrOGyIWFldR0vKIj2m0AFYAFjSMnNy8kPComPikZKA) you can try it, in the meantime I'll edit the answer – perepm Nov 02 '21 at 16:50
  • @ppicom you are right, I thought about it first and executed it on an online interpreter but it didn't work I think the problem is with that interpreter cause I tried your code on my local one and it works. I was trying to find a solution with one line of code, but it seems it could not be done. Thanks – George Saad Nov 02 '21 at 17:07
1

For example, using Object.assign

const arr = [
  {
    id: 101,
    name: 'Jone',
    age: 1
  },
  {
    id: 102,
    name: 'Jane',
    age: 2
  },
  {
    id: 103,
    name: 'johnny',
    age: 3
  }
];

Object.assign(arr.find(el => el.id === 101), {
  name: "Jimmy",
  age: 5,
});

console.log(arr);
MikeM
  • 13,156
  • 2
  • 34
  • 47