3

I have an object of 4 arrays like following

const data = {
  arr1 : [{id: 1, name: "Mike"}, {id: 2, name: "Peter"}],
  arr2 : [{id: 6, name: "John"}, {id: 9, name: "Mary"}],
  arr3 : [{id: 5, name: "Nick"}, {id: 4, name: "Ken"}],
  arr4 : [{id: 3, name: "Kelvin"}, {id: 7, name: "Steve"}, {id: 8, name: "Hank"}]
}

Then I need to find an element and update it. Here is what I tried:

const updateElement = (id: number, newName: string) => {
  let idx: number;

  idx = data.arr1.findIndex((e) => e.id === id);
  if (idx !== -1) data.arr1[idx].name = newName;

  idx = data.arr2.findIndex((e) => e.id === id);
  if (idx !== -1) data.arr2[idx].name = newName;

  idx = data.arr3.findIndex((e) => e.id === id);
  if (idx !== -1) data.arr3[idx].name = newName;

  idx = data.arr4.findIndex((e) => e.id === id);
  if (idx !== -1) data.arr4[idx].name = newName;
}

Is there any better way to update an element form multiple arrays than my approach? Suppose that every array has the same element interface.

2
  • 1
    Are the ids guaranteed to be unique or would you want to update any and all duplicates? Commented Jun 23, 2022 at 4:33
  • 1
    @Phil the id is unique and the element exists in one of 4 arrays, no duplicate Commented Jun 23, 2022 at 4:35

1 Answer 1

5

you can use Object.values() and flat() array for update it :

const data = {
  arr1 : [{id: 1, name: "Mike"}, {id: 2, name: "Peter"}],
  arr2 : [{id: 6, name: "John"}, {id: 9, name: "Mary"}],
  arr3 : [{id: 5, name: "Nick"}, {id: 4, name: "Ken"}],
  arr4 : [{id: 3, name: "Kelvin"}, {id: 7, name: "Steve"}, {id: 8, name: "Hank"}]
}
const updateElement = (id, newName) => {
  const values = Object.values(data).flat().find(ele => ele.id === id)
  if(values) values.name = newName
}
updateElement(1, 'newName')
console.log(data)

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

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.