我的问题的一个例子是这样的:
const costsArray = [
{Id: 0, type: 'store', location: ['101, 102, 103']},
{Id: 1, type: 'cost', location: ['109, 110, 111'], value: 460},
{Id: 2, type: 'cost', location: ['109, 110, 111'], value: 60000},
{Id: 3, type: 'item', location: ['109, 110, 111'], value: 460},
{Id: 4, type: 'cost', location: ['109, 110, 111'], value: 461}
]
这里有多个彼此相似的属性。我要实现的目标是:比较所有这些对象,如果任何对象的类型为'cost'and具有相同的'location'属性,则console.log表示ID:1、2、4具有不同的值。
到目前为止,我不确定,虽然不确定方向是否正确
costsArray.forEach((x: any) => {
if(x.type.name === "cost" && x.location.id === })
您的意思是这样的?
const costsArray = [
{Id: 0, type: 'store', location: '101, 102, 103'},
{Id: 1, type: 'cost', location: '109, 110, 111', value: 460},
{Id: 2, type: 'cost', location: '109, 110, 111', value: 60000},
{Id: 3, type: 'item', location: '109, 110, 111', value: 460},
{Id: 4, type: 'cost', location: '109, 110, 111', value: 461}
];
let costLocations = {};
for (let c of costsArray) {
if (c.type = 'cost') {
(costLocations[c.location] = costLocations[c.location] || []).push(c.Id);
}
}
for (let key in costLocations) {
if (costLocations[key].length > 1) {
console.log(costLocations[key] + " have different values")
}
}
const costsArray = [
{Id: 0, type: 'store', location: '101, 102, 103'},
{Id: 1, type: 'cost', location: '109, 110, 111', value: 460},
{Id: 2, type: 'cost', location: '109, 110, 111', value: 60000},
{Id: 3, type: 'item', location: '109, 110, 111', value: 460},
{Id: 4, type: 'cost', location: '109, 110, 111', value: 461}
];
console.log(
/* only get items whose type is 'cost' */
costsArray.filter(cost => cost.type === 'cost')
/* find items whose value unique */
.filter((item, i, filteredArray) => filteredArray.find(it => it.value === item.value && it.Id !== item.Id) === undefined)
/* select only the value from that item */
.map(item => item.Id)
);