在 React 应用程序中,我有这种类型的数据:
const data = {
open: [{
id: 1,
name: 'test 1'
}, {
id: 2,
name: 'test 2'
}],
close: [{
id: 3,
name: 'test 3'
}, {
id: 4,
name: 'test 4'
}]
}
我想遍历 open
和 close
数组中的每个对象,并返回带有附加 type
字段的现有数据。例如:
const data = {
open: [{
id: 1,
name: 'test 1',
type: 'alert'
}, {...],
close: [...]
}
我正在尝试这样的事情,但它返回 undefined
而不是更改后的数据:
const expandData = (data) => {
return Object.keys(data).forEach((key) => {
return data[key].map((item, idx) => ({
...item,
type: 'alert'
}))
})
}
// call in another method
expandData(data) // the `data` above
最佳答案
您可以使用 reduce()
代替 forEach()
并返回对象。
const data = {"open":[{"id":1,"name":"test 1"},{"id":2,"name":"test 2"}],"close":[{"id":3,"name":"test 3"},{"id":4,"name":"test 4"}]}
function expandData (data) {
return Object.keys(data)
.reduce((r, k) => {
r[k] = data[k].map(o => ({...o, type: 'alert'}))
return r;
}, {})
}
const result = expandData(data)
console.log(result)
关于javascript - 更改数组对象中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47632762/