如果属性存在,我试图覆盖数组中的对象title
,否则只需将其推送到数组中。我找到了两种方法,我想知道哪一种是首选。
性能并不是真正的问题,但我想知道可变性是否可能,或者只是有更好的方法来完全做到这一点。
在这个片段中,我使用 for 循环来编辑原始数组:
const data = [
{
title: 'AAA',
people: [ 'John', 'Megan',]
},{
title: 'BBB',
people: [ 'Emily', 'Tom']
}
]
// If inputTitle is not on any of data's title it will append not overwrite
// e.g. const inputTitle = 'CCC'
const inputTitle = 'AAA'
const inputPeople = ['Peter', 'Jane']
for (const obj of data) {
if (obj.title === inputTitle) {
obj.people = inputPeople
break
} else {
data.push({
title: inputTitle,
people: inputPeople
})
break
}
}
console.log(data)
在这里,我使用高阶函数并展开来做同样的事情:
const data = [
{
title: 'AAA',
people: [ 'John', 'Megan',]
},{
title: 'BBB',
people: [ 'Emily', 'Tom']
}
]
// If inputTitle is not on any of data's title it will append not overwrite
// e.g. const inputTitle = 'CCC'
const inputTitle = 'AAA'
const inputPeople = ['Peter', 'Jane']
let res = []
if (data.some(({ title }) => title === inputTitle)) {
res = data.map(obj => {
if (obj.title === inputTitle)
obj.people = inputPeople
return obj
})
} else {
res = [...data, { title: inputTitle, people: inputPeople}]
}
console.log(res)
在实际任务中,我正在data
使用节点从 json 文件中读取数组并将更改写回它。