Home > Back-end >  JavaScript modified some value in original JSON [duplicate]
JavaScript modified some value in original JSON [duplicate]

Time:10-08

I have:

const parsedData = [
  { id: 1, key: 'asdas'},
  { id: 2, key: 'asdas'},
]
parsedData.map((item, i) => ({
  ...item,
  key: `modified ${item.key}`
}));
console.log(parsedData);

What I'm trying is to get parsedData array modified and get:

[
  { id: 1, key: 'modified asdas'},
  { id: 2, key: 'modified asdas'},
]

But I'm getting the same array in the console.log

CodePudding user response:

a map will return a new array you need to capture it in different variable

const parsedData = [
  { id: 1, key: 'asdas'},
  { id: 2, key: 'asdas'},
]

const newData = parsedData.map((item, i) => ({
  ...item,
  key: `modified ${item.key}`
}));

console.log(newData);

CodePudding user response:

map returns the modified array; it does not mutate the original.

You should be logging the result returned by map:

const parsedData = [
  { id: 1, key: 'asdas'},
  { id: 2, key: 'asdas'},
]
let res = parsedData.map((item, i) => ({
  ...item,
  key: `modified ${item.key}`
}));
console.log(res);

Alternatively, you can use forEach:

const parsedData = [
  { id: 1, key: 'asdas'},
  { id: 2, key: 'asdas'},
]
parsedData.forEach((item, i) => (parsedData[i] = {
  ...item,
  key: `modified ${item.key}`
}));
console.log(parsedData);

  • Related