2

I have array with object in localstorage image

Some a function return object with new data. I need to write new data to object in localstorage (identify by ID).

I tried but... See my code below

      const result = {
        type: 'mobile',
        id: 'tsy152ivm',
        score: 55
      }

      const links = JSON.parse(localStorage.getItem('links'));
      const item = links.find(item => item.id === result.id);
      //localStorage.setItem('links', JSON.stringify(item));
1
  • please include your complete code, the current code is incomplete Commented May 26, 2019 at 17:33

2 Answers 2

2

You should get data from the storage, find an index of the target item, merge old object with a new one and store the result at the specific index, and then set the whole array at the same key. Here is a part of the most important steps:

const newData = {
  id: 'ID_2',
  NEW_DATA: 'NEW_DATA'
};

/**
 * Get old data from storage
 */

const dataFromStorage = JSON.parse(localStorage.getItem('links'));

/**
 * Merge old object with a new one (find by ID)
 */

const index = dataFromStorage.findIndex(d => d.id === newData.id);
dataFromStorage[index] = Object.assign({}, dataFromStorage[index], newData)

/**
 * Update full array in storage
 */

localStorage.setItem('links', JSON.stringify(dataFromStorage));

And here is a link to JSFIDDLE with fully working example (check the local storage after execution).

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

Comments

1

Use .findIndex() to find the index of the object you want to modify, and use Object.assign() to update the object's properties.

let arr = [{id: 34, name: 'Peter'}, {id: 'tsy152ivm', name: 'Sam'}]

const result = {
        type: 'mobile',
        id: 'tsy152ivm',
        score: 55
      }

const index = arr.findIndex(item => item.id === result.id);

const updated = [...arr.slice(0, index),Object.assign({}, arr[index], { id: result.id, name: 'Samantha' }),
...arr.slice(index + 1)
]

console.log(updated);

or just modify the object directly, using an index.

let arr = [{id: 34, name: 'Peter'}, {id: 'tsy152ivm', name: 'Sam'}]

const result = {
        type: 'mobile',
        id: 'tsy152ivm',
        score: 55
      }

const index = arr.findIndex(item => item.id === result.id);


arr[index] = Object.assign({}, arr[index], { name: 'Samantha'})

console.log(arr);

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.