javascript 将对象中的值与js中的另一个数组匹配

a11xaf1n  于 2022-12-21  发布在  Java
关注(0)|答案(3)|浏览(213)

你好,我有一个数组对象,我必须从对象中找到与下面的数组键匹配的值,我尝试了数组和对象,但没有得到结果

var filterkey = [a,b,c];
var palistarray = [{
{
            "Id": 199,
            "a": "Rajesh Tamore",
            "b": "23/11/2022",
            "c": "23/11/2022",
            "d": "W"
        },
        {
            "Id": 200,
            "a": "Sunil N",
            "b": "21/11/2022",
            "c": "21/11/2022",
            "d": "S"
        },
}]

我希望结果如下

[{
{
            "a": "Rajesh Tamore",
            "b": "23/11/2022",
            "c": "23/11/2022",
        },
        {
            "a": "Sunil N",
            "b": "21/11/2022",
            "c": "21/11/2022",
        },
}]

我已经尝试下面的代码

palistarray.find((item,index) => {
    console.log(item[filterkey[index]]);
  });
4si2a6ki

4si2a6ki1#

尝试使用数组.原型.Map()、**对象.键()对象.原型.hasOwnProperty()**函数,如下所示:

const result = palistarray.map((obj) => {
    const newObj = {};
    Object.keys(obj).forEach((key) => {
        if (filterkey.includes(key) && obj.hasOwnProperty(key)) {
            newObj[key] = obj[key];
        }
    });
    return newObj;
});
q8l4jmvw

q8l4jmvw2#

您可以编写自己的函数,如下所示:

const filterkey = ['a', 'b', 'c']

const palistarray = [
  {
    'Id': 199,
    'a':  'Rajesh Tamore',
    'b':  '23/11/2022',
    'c':  '23/11/2022',
    'd':  'W',
  }, {
    'Id': 200,
    'a':  'Sunil N',
    'b':  '21/11/2022',
    'c':  '21/11/2022',
    'd':  'S',
  },
]

const filterBy = (array, predicate) => array.map(value => {
  const result = {}

  predicate.forEach(key => {
    if (value[key]) {
      result[key] = value[key]
    }
  })

  return result
})

const result = filterBy(palistarray, filterkey)

console.log(result)

最好的问候!

yeotifhr

yeotifhr3#

我不得不假设你的数组应该是这样的,没有额外的花括号:

var palistarray = [{

            "Id": 199,
            "a": "Rajesh Tamore",
            "b": "23/11/2022",
            "c": "23/11/2022",
            "d": "W"
        },
        {
            "Id": 200,
            "a": "Sunil N",
            "b": "21/11/2022",
            "c": "21/11/2022",
            "d": "S"
       },
];

一个非常简单的方法是:

const filterArray = ["a", "b", "c"];

const palistarray = [{

            "Id": 199,
            "a": "Rajesh Tamore",
            "b": "23/11/2022",
            "c": "23/11/2022",
            "d": "W"
        },
        {
            "Id": 200,
            "a": "Sunil N",
            "b": "21/11/2022",
            "c": "21/11/2022",
            "d": "S"
       },
];

const mapped = palistarray.map(item => {
  const data = {};
  filterArray.forEach(key => {
    data[key] = item[key];
  })
  return data;
});

console.log(mapped);

这只是从对象Map和返回指定键的一种情况

相关问题