首页 > 解决方案 > 检查数组中的多个对象并比较对象中的某些属性何时满足条件

问题描述

我的问题的一个例子是这样的:

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 说 Id: 1、2、4 具有不同的值。

到目前为止我有什么,但不确定方向是否正确

costsArray.forEach((x: any) => {
   if(x.type.name === "cost" && x.location.id === })

标签: javascriptarraystypescript

解决方案


你的意思是这样的?

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")  
  }
}


推荐阅读