【问题标题】:Get `val` of property from array of objects inside array of objects based on other property of the object根据对象的其他属性从对象数组中的对象数组中获取属性的“值”
【发布时间】:2020-03-29 16:51:32
【问题描述】:
var arr = [{req: [{type: 'high', val: 1},{type: 'low', val: 2}], other: [{random: 123}]}, {req: [{type: 'cool', val: 1},{type: 'med', val: 3}], other: [{random: 456}]}]

如何使用数组函数编写函数以从对象数组内部的对象数组中获取val 的值,其中typemed

预期结果

var result = 3;

我尝试使用数组的reduce函数

let getRequirementArray = (req, vol) =>
  req.reduce((currentVal, obj) => {
    return obj.type === vol ? obj.val + currentVal : currentVal;
  }, 0);

let getFinalOutput = (arr, vol) =>
  arr.reduce((currentVal, obj) => {
    let { req } = obj;
    let val= getRequirementArray(req, vol);
    return val + currentVal;
  }, 0);
var result = getFinalOutput(arr, 'med');

但我希望功能更小

【问题讨论】:

  • 带有other 键的对象可以包含类型:med 吗?
  • @ShubhamKhatri,只有req 包含type 'med',如果req 对象数组中有多个'med' 类型,就我而言,我只需要首先考虑发生它并返回val属性
  • 我根据这个假设添加了我的答案

标签: javascript arrays object ecmascript-6


【解决方案1】:

您可以将数组聚合成单个对象数组,然后找到type 等于med 的对象

var arr = [{req: [{type: 'high', val: 1},{type: 'low', val: 2}], other: [{random: 123}]}, {req: [{type: 'cool', val: 1},{type: 'med', val: 3}], other: [{random: 456}]}]

var mix = [].concat(...arr.map(t => t.req));
var obj = mix.find(x => x.type === 'med');
console.log(obj.val);

【讨论】:

    【解决方案2】:

    你可以使用数组的每一个函数,当你得到第一个值时返回false

    var value,arr = [{req: [{type: 'high', val: 1},{type: 'low', val: 2}], other: [{random: 123}]}, {req: [{type: 'cool', val: 1},{type: 'med', val: 3}], other: [{random: 456}]}]
    arr.every(outerObject => {let desObj = outerObject.req.find(obj => obj.type == "med");if (desObj){value=desObj.val;return false;}return true;   
    });
    console.log(value);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-12
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      • 2020-04-28
      • 2022-10-19
      • 2011-05-27
      • 1970-01-01
      相关资源
      最近更新 更多