-2

In the below array of arrays I need to update the id value for a particular name.

objArray = [{ name: John, id: 12}, { name: Jake, id: 45}, { name: Jacob, id: 78}];

Ex: If user enters a name and id in text boxes and clicks submit I want to update the id in the array for the particular name.

I can accomplish this using for loops but can you please let me know the most efficient way to do this in Java Script/React?

Nitheesh
  • 47
  • 8

2 Answers2

0

Use the find function and set the entered name.

Look at this code snippet

let objArray = [{  name: "John",  id: 12}, {  name: "Jake",  id: 45}, {  name: "Jacob",  id: 78}];

let name = 'Jake'
let newId = 59;
objArray.find((o) => o.name === name).id = newId;

console.log(objArray);
.as-console-wrapper {
  max-height: 100% !important
}
Ele
  • 33,468
  • 7
  • 37
  • 75
0

You can use findIndex to get the index of the object whose name matches. Then use that index to update the id

var objArray = [{
  name: 'John',
  id: 12
}, {
  name: 'Jake',
  id: 45
}, {
  name: 'Jacob',
  id: 78
}];

function update() {
  var getVal = document.getElementById('ip').value.trim();
  var getIndex = objArray.findIndex(function(item) {
    return item.name.toLowerCase() === getVal.toLowerCase();
  })
  objArray[getIndex].id= "newId"
  console.log(objArray)
}
<input type="text" id="ip">
<button onclick="update()">Update</button>
brk
  • 48,835
  • 10
  • 56
  • 78
  • Thanks brk! This solved my problem too but I would go with Ele's answer. I want to give you a one up but I dont have enough reps! – Nitheesh Feb 08 '18 at 16:06