0

Given an array with some object:

let array = [
  { name: 'bob', score: 12 },
  { name: 'Joe', score: 20 },
  { name: 'Sue', score: 25 }
]

How can I replace Joe's object in the array with this new object in a single line:

let newScoreForJoe = { name: 'Joe', score: 21 }

I know that I can find the index of Joe's object in the array and then update it like so:

let joeIndex = array.findIndex(x => x.name === newScoreForJoe.name)
array[joeIndex] = newScoreForJoe;

But is there an elegant one-liner to achieve the same thing?

5
  • 1
    Well you could get rid of the joeIndex and just do array[array.findIndex(x => x.name === newScoreForJoe.name)] = newScoreForJoe; Commented May 19, 2017 at 9:03
  • I think there will be no better solution, the 'name' property has no special rule to find. Commented May 19, 2017 at 9:07
  • did you check y answer? Commented May 19, 2017 at 9:12
  • @DragoşPaulMarinescu this is the best one. If you add it as an answer I will accept Commented May 19, 2017 at 9:13
  • @railsuser400 sure, just added. glad that helped. Commented May 19, 2017 at 9:16

4 Answers 4

1

You can simply get rid of the joeIndex variable all together and just do:

array[array.findIndex(x => x.name === newScoreForJoe.name)] = newScoreForJoe;

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

Comments

1

I'm sure how elegant this will be for you but since you are trying to returm an array with the same amuount of objects, i would do this:

The array:

let array = [
  { name: 'bob', score: 12 },
  { name: 'Joe', score: 20 },
  { name: 'Sue', score: 25 }
]

The object:

let newScoreForJoe = { name: 'Joe', score: 21 }

The replace line:

let joeIndex = array.map(x => x.name === newScoreForJoe.name ? newScoreForJoe : x)

Comments

0

You can try this answer. Just change the value of the object property.

array[1].score = 21;

1 Comment

This doesn't answer the question.
0

You could use Array#some and assign the new object inside of the callback.

If no object is found, no assignment happens.

let array = [{ name: 'bob', score: 12 }, { name: 'Joe', score: 20 }, { name: 'Sue', score: 25 }],
    newScoreForJoe = { name: 'Joe',score: 21 };
    
array.some((a, i, aa) => (a.name === newScoreForJoe.name && (aa[i] = newScoreForJoe)));

console.log(array);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.