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
  • 770
  • 4
  • 11
ttmt
  • 5,822
  • 27
  • 106
  • 158
  • [Filter object properties by key in ES6](https://stackoverflow.com/questions/38750705/filter-object-properties-by-key-in-es6) – Alona Jun 18 '19 at 08:21

9 Answers9

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).

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
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)
George Wang
  • 451
  • 2
  • 12
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)
ellipsis
  • 12,049
  • 2
  • 17
  • 33
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));
StepUp
  • 36,391
  • 15
  • 88
  • 148
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.

Nicolae Maties
  • 2,476
  • 1
  • 16
  • 26
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)
void
  • 36,090
  • 8
  • 62
  • 107
1
cont objCopy = Object.entries(obj).reduce(([key, value],acc)=>keys.includes(key)?{...acc, key:value}:acc, {}) 
Will Jenkins
  • 9,507
  • 1
  • 27
  • 46
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,609
  • 15
  • 24
LiefdeWen
  • 586
  • 2
  • 14
  • +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` – codeherk Jun 18 '19 at 08:11
  • 1
    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. – Alona Jun 18 '19 at 08:13
  • 1
    @АленаВерещака I addressed your concerns – LiefdeWen Jun 18 '19 at 08:27
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))
Ghoul Ahmed
  • 4,446
  • 1
  • 14
  • 23
  • 1
    It's not the answer for this Question. If you need additional property `four` then how much do you need to update? – Alona Jun 18 '19 at 08:15
  • 1
    @АленаВерещака ,add in params , ({, four}) , i use destructuring objects as function parameters in ES6..., this is solution without using any iterations (foreach, map ...) – Ghoul Ahmed Jun 18 '19 at 08:21
  • 1
    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 – Alona Jun 18 '19 at 08:24