如何通过字符串数组过滤对象字段

时间:2019-08-30 18:38:56

标签: arrays object filter

如何通过字符串数组过滤对象的字段?

例如

catValues:{
    "1":{
        value:10,
        code:5
     },
    "3":{
        value:10,
        code:5
     },
    "5":{
        value:10,
        code:5
     }
}


var chosenCats = ["1","5"]

result: {"1":{value:10, code:5}, "5":{value:10, code:5}}

2 个答案:

答案 0 :(得分:1)

您创建一个新对象,然后仅插入选定的cat值。

<div class="personalPhoto"><img src="images/camera.png"></div>

或者您可以使用filter()reduce()

var chosenCatValues = {};

for (var cat of chosenCats) {
  chosenCatValues[cat] = catValues[cat];
} 

演示:

var chosenCatValues = Object.keys(catValues)
  .filter(key => chosenCats.includes(key))
  .reduce((obj, key) => {
    obj[key] = catValues[key];
    return obj;
  }, {});

答案 1 :(得分:0)

尝试一下:

注意:这同样适用于字符串数组,因为它们是数字。

var catValues = {
    "1":{
        value:10,
        code:5
     },
    "3":{
        value:10,
        code:5
     },
    "5":{
        value:10,
        code:5
     }
}

var chosen = ['1','5'];

const func = (chosen, catValues) => {
    var ch = {};
    chosen.map(chose => {
      if(chose in catValues) {
        ch[chose] = catValues[chose]
      }
  })
  return ch
}

console.log(func(chosen, catValues))