在对象数组中,将所有以前的对象修改为具有特定特性的对象



我有一个对象数组,根据其中一个插入的属性,我想标记或选择特定属性的对象容器之前的所有对象

我的数组是这样的:

const arrX= [
{ status: '1' },
{ status: '2'},
{ status: '3', imHere: true },
{ status: '4' },
];

然后,由于arrX[2]上的属性imHere,应该修改位置arrX[0]和arrX[1]。

我的预期结果是:

const arrX= [
{ status: '1',wasHere:true },
{ status: '2',wasHere:true},
{ status: '3', imHere: true },
{ status: '4' },
];

我知道map方法在这种情况下会很有用,但找不到从包含imHere的对象的索引向后检查前者位置的方法

一种方法是使用.findIndex().map():

const arrX= [{ status: '1' }, { status: '2'}, { status: '3', imHere: true }, { status: '4'}];
const imHereIndex = arrX.findIndex(({imHere}) => imHere === true);
const result = arrX.map((val, index) => index < imHereIndex
? { ...val, wasHere: true }
: val
);
console.log(result);

即使@Kinglish的回答很有魅力,我也想分享另一种实现你目标的方法。这条路肯定比Kinglish的长,永远不会少是一个很好的选择。

{ status: '4' },
];

function findProperty(arr) {
const hasProperty = arr.findIndex(el => Object.keys(el).includes('imHere'))
const addNewProperty = arr.map((el,i) => (i < hasProperty) ? {...el, wasHere: true} : el)

return addNewProperty
}
const updatedArray = findProperty(arrX)
console.log(updatedArray)

这里有一个方法,它使用Array#reduce和布尔值来跟踪我们是否遇到了inHere

const arrX = [
{status: '1'},
{status: '2'},
{status: '3',imHere: true},
{status: '4'},
];
let found = false,
updated = arrX.reduce((b, a) => {
found = found || (a.hasOwnProperty('imHere') && a.imHere === true)
if (!found) a.wasHere = true;
return b.concat(a);
}, [])
console.log(updated)

一个简单的循环-当其中一个对象包含imHere时,会中断它,否则会添加wasHere属性。

function update(arr) {
for (let i = 0; i < arr.length; i++) {
if (!arr[i].imHere) {
arr[i].wasHere = true;
} else {
break;
}
}
return arr;
}
const arr = [
{ status: '1' },
{ status: '2' },
{ status: '3', imHere: true },
{ status: '4' },
];
console.log(update(arr));

最新更新