Reputation: 91
I want to remove unnecessary key values pairs in a user object based on an array, essentially a whitelist. I have looked at reduce()
, filter()
and map()
but can't quite get the implementation to work.
Here is my code currently
const user = {
"email": "[email protected]"
"name": "Bob"
"surname": "Smith"
};
const userFields = [`email`, `name`]; // array of whitelist
Before I iterate through the object properties, I'd like to reduce Object to have fields only in the array whitelist, so our man Bob Smith would end up like this
const user = {
"email": "[email protected]"
"name": "Bob"
};
Thanks!
Upvotes: 1
Views: 1008
Reputation: 3302
You could use Object.fromEntries()
method. Traverse the userFields
array using Array.prototype.map()
and make a list of key-value
pair array. At last, from that list transform it into the required object by using Object.entries()
method.
const user = {
email: '[email protected]',
name: 'Bob',
surname: 'Smith',
};
const userFields = [`email`, `name`];
const ret = Object.fromEntries(userFields.map((x) => [x, user[x]]));
console.log(ret);
Upvotes: 0
Reputation: 1074305
For me, the simplest thing to do would be to loop through the passlist and build an object:
const result = {};
for (const name of userFields) {
result[name] = user[name];
}
Live Example:
const user = {
"email": "[email protected]",
"name": "Bob",
"surname": "Smith",
};
const userFields = [`email`, `name`];
const result = {};
for (const name of userFields) {
result[name] = user[name];
}
console.log(result);
You could use map
and Object.fromEntries
, but I don't think it buys you anything:
const result = Object.fromEntries(
userFields.map(name => [name, user[name]])
);
Live Example:
const user = {
"email": "[email protected]",
"name": "Bob",
"surname": "Smith",
};
const userFields = [`email`, `name`];
const result = Object.fromEntries(
userFields.map(name => [name, user[name]])
);
console.log(result);
FWIW, for me reduce
is the wrong tool for this (or indeed, almost anything else outside of Functional Programmning with predefined, reusable reducer functions), not least because the accumulator in a reduce
solution would never change (it's always the same object). reduce
where a simple loop suffices is just overcomplicated and easy to get wrong. (An opinion which isn't solely mine, btw.)
Upvotes: 0
Reputation: 11001
Use reduce
on userFields and build
const user = {
email: "[email protected]",
name: "Bob",
surname: "Smith",
};
const userFields = [`email`, `name`];
const newUser = userFields.reduce(
(acc, key) => Object.assign(acc, { [key]: user[key] }),
{}
);
console.log(newUser)
Upvotes: 1