0

I have an array with names in.

I also have an object with keys that are the same as those in the array. The object also has other keys.

I would like to copy the object but only include the keys that are in the array

const keys = ['one', 'two', 'three'];
const obj = {
	date: 'Jan',
	color: 'Red',
	one: 367,
	two: 427,
	three: 753
}
const objCopy = Object.assign({}, obj)
// I'd like this console to display
// {
// "one": 367,
// "two": 427,
// "three": 753
// }
console.log(objCopy)

Ammar
8185 silver badges12 bronze badges
asked Jun 18, 2019 at 8:02
1

9 Answers 9

4

Very simple reduce.

const keys = ['one', 'two', 'three'];
const obj = {
 date: 'Jan',
 color: 'Red',
 one: 367,
 two: 427,
 three: 753
};
const res = keys.reduce((a, c) => (obj[c] ? a[c] = obj[c] : c, a), {});
console.log(res);

(The ternary operator ensures that the key actually exists in the object - otherwise you'd get undefineds in your result that you'd have to filter out).

answered Jun 18, 2019 at 8:10

Comments

3

const keys = ['one', 'two', 'three'];
const obj = {
	date: 'Jan',
	color: 'Red',
	one: 367,
	two: 427,
	three: 753
}
const objCopy = {};
keys.forEach(key => objCopy[key] = obj[key]);
console.log(objCopy)

answered Jun 18, 2019 at 8:09

Comments

2

Using forEach loop

const keys = ['one', 'two', 'three'];
const obj = {
	date: 'Jan',
	color: 'Red',
	one: 367,
	two: 427,
	three: 753
}
var obj1={};
keys.forEach(e=>{
obj1[e]=obj[e]
})
const objCopy = Object.assign({}, obj1)
console.log(objCopy)

answered Jun 18, 2019 at 8:07

Comments

2

It is possible to get the desired object using the following way:

const keys = ['one', 'two', 'three'];
const obj = {
 date: 'Jan',
 color: 'Red',
 one: 367,
 two: 427,
 three: 753
}
let desiredObject = Object.keys(obj)
 .filter(key => keys.includes(key))
 .map(key => {
 return {[key]: obj[key]}
 })
 .reduce((a, b) => Object.assign({}, a,b));
answered Jun 18, 2019 at 8:15

Comments

1

This might help you, you have to loop through the keys array and add grab every existing key from obj in order to construct your new object. Which is not a copy, it's a new object with your desired keys.

const keys = ['one', 'two', 'three'];
const obj = {
	date: 'Jan',
	color: 'Red',
	one: 367,
	two: 427,
	three: 753
}
const objCopy = {};
for (let i = 0; i < keys.length; i++) {
 objCopy[keys[i]] = obj[keys[i]];
}
console.log(objCopy)

You don't need to use any other fancy methods to do this, other methods will indeed reduce the number of the code lines but will decrease your performance, like using .reduce() or other Array methods.

answered Jun 18, 2019 at 8:06

Comments

1

You can use .reduce on the keys array to get the desired object.

const keys = ['one', 'two', 'three'];
const obj = {
	date: 'Jan',
	color: 'Red',
	one: 367,
	two: 427,
	three: 753
}
const objCopy = keys.reduce((a,e) => {
 a[e] = obj[e];
 return a;
}, {});
console.log(objCopy)

answered Jun 18, 2019 at 8:07

Comments

1
cont objCopy = Object.entries(obj).reduce(([key, value],acc)=>keys.includes(key)?{...acc, key:value}:acc, {}) 
answered Jun 18, 2019 at 8:08

Comments

1

Try this:

const obj = {
	date: 'Jan',
	color: 'Red',
	one: 367,
	two: 427,
	three: 753
}
const extract = ({one, two, three}) =>Object.assign({},{one, two, three});
console.log(extract(obj))

answered Jun 18, 2019 at 8:10

3 Comments

It's not the answer for this Question. If you need additional property four then how much do you need to update?
@АленаВерещака ,add in params , ({, four}) , i use destructuring objects as function parameters in ES6..., this is solution without using any iterations (foreach, map ...)
Ahmen, thanks for your reply. I think the point of question is asking how to copy object by filtering key array which consist string keys inside. Thanks
1

The hasOwnProperty is used to exclude inherited properties

const keys = ['one', 'two', 'three'];
const obj = {
 date: 'Jan',
 color: 'Red',
 one: 367,
 two: 427,
 three: 753
}
const objCopy = {}; // copy
for (let property in obj) {
 if (obj.hasOwnProperty(property) && keys.find(k => k == property)) {
 objCopy[property] = obj[property];
 }
}
console.log(objCopy);

codeherk
1,65716 silver badges24 bronze badges
answered Jun 18, 2019 at 8:09

3 Comments

+1 for checking if it has the property. I suggested an edit to have let inside for loop. we should use let and const in JS and retire use of var
First your code is wrong - duplicated obj declaration. And for object - it's better to use const than let if you don't need assignment another value.
@АленаВерещака I addressed your concerns

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.