I want to pass a function an array of keys and an object, and return a new object that only contains the key/value pairs that I specify in the keys array.
So if I had an object like this:
{"name" : "John Smith", "position" : "CEO", "year" : "2019" }
And I passed the array
["name", "year"]
the new object returned would be:
{"name" : "John Smith", "year" : "2019" }
I've been playing around with it, but my code is not working.
function parse(keys, data) {
let obj = JSON.parse(data);
let newObj = {};
keys.array.forEach(element => {
newObj[element] = obj.element;
});
return newObj;
};
You dont need to do parse.Secondly this line keys.array.forEach is wrong. This is because there is no array key inside keys.Also replace obj.element; with data[element]
let data = {
"name": "John Smith",
"position": "CEO",
"year": "2019"
}
let keys = ["name", "year"]
function parse(keys, data) {
let newJson = {};
keys.forEach(element => {
newJson[element] = data[element];
});
return newJson;
};
console.log(parse(keys, data))
One way to achieve this would be through filtering an array of object entries:
const entries = Object.entries({
"name" : "John Smith",
"position" : "CEO",
"year" : "2019"
})
entries contains:
[
[
"name",
"John Smith"
],
[
"position",
"CEO"
],
[
"year",
"2019"
]
]
Filtering out keys:
const filteredEntries = entries.filter(([ key ]) => ["name", "year"].includes(key))
filteredEntries contains:
[
[
"name",
"John Smith"
],
[
"year",
"2019"
]
]
Last step - construct an object:
const filteredObject = Object.fromEntries(filteredEntries)
filteredObject contains:
{
"name": "John Smith",
"year": "2019"
}
Putting it together as a function:
function filterObjectByGivenKeys(object, keys) {
const filteredEntries = Object
.entries(object)
.filter(([ key ]) => keys.includes(key))
return Object.fromEntries(filteredEntries)
}
Or, if we prefer reduce and more terse syntax:
const filterObjectByGivenKeys = (object, keys) =>
Object.entries(object)
.filter(([ key ]) => keys.includes(key))
.reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With