Hello i have an array object i have to find values from object with match array keys below is array and object i tried but not getting the result
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",
},
}]
i had tries below code
palistarray.find((item,index) => {
console.log(item[filterkey[index]]);
});
Try using the Array.prototype.map() , Object.keys() and Object.prototype.hasOwnProperty() functions like this:
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;
});
You can write your own function, like this:
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)
Best regards!
I have to presume your array should be this, without the extra curly braces:
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 really simple way would be this:
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);
It's just a case of mapping and returning the specified keys from the objects
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.