javascript - ES6 : Find an object in an array by one of its properties

标签 javascript arrays

我正在尝试弄清楚如何在 ES6 中执行此操作...

我有这个对象数组..

const originalData=[
{"investor": "Sue", "value": 5, "investment": "stocks"},
{"investor": "Rob", "value": 15, "investment": "options"},
{"investor": "Sue", "value": 25, "investment": "savings"},
{"investor": "Rob", "value": 15, "investment": "savings"},
{"investor": "Sue", "value": 2, "investment": "stocks"},
{"investor": "Liz", "value": 85, "investment": "options"},
{"investor": "Liz", "value": 16, "investment": "options"}
];

..以及这个新的对象数组,我想在其中添加每个人的投资类型(股票、期权、储蓄)的总值(value)..

const newData = [
{"investor":"Sue", "stocks": 0, "options": 0, "savings": 0},
{"investor":"Rob", "stocks": 0, "options": 0, "savings": 0},
{"investor":"Liz", "stocks": 0, "options": 0, "savings": 0}
];

我循环访问originalData并将“当前对象”的每个属性保存在let中..

for (let obj of originalData) {
   let currinvestor = obj.investor;
   let currinvestment = obj.investment;
   let currvalue = obj.value;

   ..but here I want to find the obect in newData that has the property = currinvestor (for the "investor" key)
   ...then add that investment type's (currinvestment) value (currvalue) 
}

最佳答案

newData.find(x => x.investor === investor)

整个代码:

const originalData = [
  { "investor": "Sue",   "value":  5,   "investment": "stocks"  },
  { "investor": "Rob",   "value": 15,   "investment": "options" },
  { "investor": "Sue",   "value": 25,   "investment": "savings" },
  { "investor": "Rob",   "value": 15,   "investment": "savings" },
  { "investor": "Sue",   "value":  2,   "investment": "stocks"  },
  { "investor": "Liz",   "value": 85,   "investment": "options" },
  { "investor": "Liz",   "value": 16,   "investment": "options" },
];

const newData = [
  { "investor": "Sue",   "stocks": 0,   "options": 0,   "savings": 0 },
  { "investor": "Rob",   "stocks": 0,   "options": 0,   "savings": 0 },
  { "investor": "Liz",   "stocks": 0,   "options": 0,   "savings": 0 },
];

for (let {investor, value, investment} of originalData) {
  newData.find(x => x.investor === investor)[investment] += value;
}

console.log(newData);
.as-console-wrapper.as-console-wrapper { max-height: 100vh }

关于javascript - ES6 : Find an object in an array by one of its properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39235353/

相关文章:

javascript - 数组中最大的总和,无需添加 2 个连续值

arrays - 如何在 Swift 中创建二维数组?

arrays - 在 golang 中 [:] syntax differ from the array assignment?

javascript - 在发布到 API 之前更改数组 javascript 中的一些值

javascript - 如何在 Ajax 期间迭代嵌套 JSON?

Javascript,如何用点分割键来恢复json结构

javascript - 删除图片 uploader 上的图片

javascript - 打开每个图像后 Loading.gif 不工作-灯箱 2

javascript - 有什么方法可以修复我的服务器问候语吗?

java - 如何在不使用预制类的情况下在 Java 中创建可扩展动态数组?