-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
  • 2
    Just assign the result of find to a var, then you change all the properties you want. Commented Nov 2, 2021 at 16:33
  • your code cannot pass the interpreter you are using illegal characters ( the quotes “ ... ” ) Commented Nov 2, 2021 at 16:38

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

2 Comments

I was trying to find a solution with one line of code, but it seems it could not be done. Thanks
I think that's one line of code :D, also you should mention it in the question
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);

4 Comments

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.
That's not true. Objects are passed by reference (most of the time). I strongly recommend that you check out this answer in stack overflow that explains it, and that you research a little bit more about the subject :)
I copy pasted from the question. Here you can try it, in the meantime I'll edit the answer
@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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.