在对象数组中查找对象

时间:2019-02-11 11:40:48

标签: javascript typescript

我有一个对象的nsted数组

0: "0"
1: Array(3)
  0: {Situation A: "5.0"}
  1: {Situation B: "4.0"}
  2: {Situation C: 0}
0: "1"
1: Array(3)
  0: {Situation B: "6.0"}
  1: {Situation C: "4.0"}
  2: {Situation A: 2.0}
...

例如,我将得到一个值为Situation B的数组。

这是预期的输出(值数组)

0: "4.0"
1: "6.0"

这就是我的方式

this.data = _.isArray(this.valuesCopy) // check if array
  ? this.valuesCopy.map(_val => { // then 
    let value
      if (_val[1] !== null) {
         value =_val[1].filter(obj => {
          if(Object.keys(obj).find(key=>key=="Situation B")) { // check if Situation B exist
            return obj;
          }
        });
      }
      return value[0]["Situation B"]

    })
  : []

在我的控制台中出现错误

 Cannot read property 0' of undefined

7 个答案:

答案 0 :(得分:0)

您可以执行递归功能,或展平,过滤和映射。

以下是使用新的flat数组方法的展平,过滤和映射版本(您可以在必要时进行填充):

const result = this.valuesCopy
                .flat(2)
                .filter(obj => Object.prototype.hasOwnProperty.call(obj, "Situation B"))
                .map(obj => obj["Situation B"]);

实时示例:

const valuesCopy = [
    "0",
    [
      {"Situation A": "5.0"},
      {"Situation B": "4.0"},
      {"Situation C": 0}
    ],
    "1",
    [
      {"Situation B": "6.0"},
      {"Situation C": "4.0"},
      {"Situation A": 2.0}
    ]
];
const result = valuesCopy
                .flat(2)
                .filter(obj => Object.prototype.hasOwnProperty.call(obj, "Situation B"))
                .map(obj => obj["Situation B"]);
console.log(result);

或递归解决方案:

function deepPick(data, propName, resultArray = []) {
    for (const entry of data) {
        if (Array.isArray(entry)) {
            deepPick(entry, propName, resultArray);
        } else if (Object.prototype.hasOwnProperty.call(entry, propName)) {
            resultArray.push(entry[propName]);
        }
    }
    return resultArray;
}

const result = deepPick(this.valuesCopy, "Situation B");

实时示例:

function deepPick(data, propName, resultArray = []) {
    for (const entry of data) {
        if (Array.isArray(entry)) {
            deepPick(entry, propName, resultArray);
        } else if (Object.prototype.hasOwnProperty.call(entry, propName)) {
            resultArray.push(entry[propName]);
        }
    }
    return resultArray;
}

const valuesCopy = [
    "0",
    [
      {"Situation A": "5.0"},
      {"Situation B": "4.0"},
      {"Situation C": 0}
    ],
    "1",
    [
      {"Situation B": "6.0"},
      {"Situation C": "4.0"},
      {"Situation A": 2.0}
    ]
];
const result = deepPick(valuesCopy, "Situation B");
console.log(result);


显然,您可以根据需要调整Object.prototype.hasOwnProperty(x, name)。例如,您可以在其前面添加typeof x === "object" &&,以避免在条目不是一个的情况下hasOwnProperty创建对象等。

答案 1 :(得分:0)

使用Array#flat,Array#map,Array#filter和解构。

const data = [
    [
      {"Situation A": "5.0"}, {"Situation B": "4.0"}, {"Situation C": 0}
    ],
    [
      {"Situation B": "6.0"}, {"Situation C": "4.0"}, {"Situation A": 2.0}
    ]
]

const res = data
  .flat()
  .map(Object.entries)
  .flat()
  .filter(([k])=>k==="Situation B")
  .map(([,v])=>v);

console.log(res);

答案 2 :(得分:0)

根据您发布的代码,我假设这是您的结构。您可以使用flatbody { background-color: rgb(0, 195, 255); }

做类似的事情

filter

如果您的浏览器中有const valuesCopy = [ ["0", [{ "Situation A": "5.0" }, { "Situation B": "4.0" }, { "Situation C": 0 } ]], ["1", [{ "Situation B": "6.0" }, { "Situation C": "4.0" }, { "Situation A": 2.0 } ]] ]; const output = valuesCopy.map(a => a[1] ? a[1] : []) .flat() .filter(a => "Situation B" in a) .map(a => a["Situation B"]) console.log(output) isn't supported

flat

答案 3 :(得分:0)

您可以使用flatreduce

const data = [[{"Situation A": "5.0"}, {"Situation B": "4.0"}, {"Situation C": 0}],[{"Situation B": "6.0"}, {"Situation C": "4.0"}, {"Situation A": 2.0}]]

const res = data.flat()
  .reduce((op,inp)=>{
    if(Object.keys(inp)[0] === 'Situation B'){
      op.push(inp['Situation B'])
    }
    return op
  },[])

console.log(res);

答案 4 :(得分:0)

这可能不是一个很好的解决方案,但是您可以尝试

const ar = [
  [
   '0',
    [{ 'Situation A': '5.0' }, { 'Situation B': '4.0' 
     }, { 'Situation C': 0 }]
  ],
 [
   1,
   [{ 'Situation B': '6.0' }, { 'Situation C': '4.0' 
    }, { 'Situation C': 2.0 }]
   ]
 ];

const output = [];
ar.forEach(ele => {
 ele[1].forEach(arData => {
  if (arData.hasOwnProperty('Situation B')) {
  output.push(arData['Situation B']);
    }
  });
});


console.log(output);

答案 5 :(得分:-1)

遍历子数组,检查键是否在对象中,以及是否将结果添加到数组中。

var arrs = [[{"Situation A": "5.0"},
              {"Situation B": "4.0"},
              {"Situation C": 0}],
              [{"Situation B": "6.0"},
              {"Situation C": "4.0"},
              {"Situation A": 2.0}]];

var key = "Situation B";

var matches = [];
arrs.forEach(function(arr) {
  arr.forEach(function(o) {
    if (key in o) {
      matches.push(o[key]);
    }
  })
})

console.log(matches);

答案 6 :(得分:-1)

目前尚不清楚数据的完整结构是什么。我认为:

const values = [
    [
        "0",
        [
            {"Situation A": "foo"},
            {"Situation B": "bar"},
            {"Situation C": "baz"}
        ]
    ],
    [
        "1",
        [
            {"Situation A": "foo"},
            {"Situation B": "bar"},
            {"Situation C": "baz"}
        ]
    ],
    ...
]

我认为这应该可行:

values
  .map(x => x[1] || [])
  .flat()
  .filter(x => x.hasOwnProperty('Situation B') && x['Situation B'])
  .map(x => x['Situation B'])