javascript - 检查数组中的多个对象并比较对象中的某些属性何时满足条件
问题描述
我的问题的一个例子是这样的:
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 === })
解决方案
你的意思是这样的?
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")
}
}
推荐阅读
- java - SVG 文件的路径
- node.js - 在 Nuxt 中使用节点子路径导出
- python - Python 本地包导入失败
- r - 如何使用ggplot2删除条形图中线型图例的默认灰色填充?
- python-3.x - 使用 kivy 在 python 中创建忘记密码屏幕的问题
- c++ - C++ OOP 私有变量改变值本身
- oracle12c - 将 Google Maps GeocodingApi 检索到的坐标存储在 Oracle 数据库中,并使用 SDO_GEOM.SDO_DISTANCE 计算它们之间的距离
- ansible - 无法在ansible中运行脚本
- powershell - 在 Jenkins 中执行 powershell 文件失败,`xx.ps1 未进行数字签名。您无法在当前系统上运行此脚本`
- bots - https://developers.google.com/+/web/snippet/ 这是一个爬虫机器人吗