[英]match value from object to another array in js
你好,我有一個數組對象,我必須從具有匹配數組鍵的對象中找到值,下面是數組和對象,我試過但沒有得到結果
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"
},
}]
i want result like below
[{
{
"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]]);
});
嘗試像這樣使用Array.prototype.map() 、 Object.keys()和Object.prototype.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;
});
您可以編寫自己的函數,如下所示:
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)
最好的祝福!
我必須假設你的數組應該是這樣的,沒有額外的花括號:
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);
這只是映射並從對象返回指定鍵的情況
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.