Home > OS >  How to deep clone object properties specified in array TS/JS
How to deep clone object properties specified in array TS/JS

Time:06-22

How to make a deep copy of an object properties specified in array. For instance i have an object {a: 1, b: 2, c: 3} And an array ["a", "b"]. I want to deeply clone only the specified properties in object, so i need to get something like this {a: 1, b: 2}. Is there an easy way to do that?

CodePudding user response:

Hope it will work for you.


const array= ["a","b"]
const obj = {
  a: 1,
  b:2,
  c:3
}

const copyObj= { }
array.forEach((e)=>{
   copyObj[e] = obj[e]? obj[e]: null
})


CodePudding user response:

You can iterate over your object keys with Object.keys()

const keys = Object.keys(yourObject);
keys.forEach((key, index) => {
console.log(`${key}: ${yourObject[key]}`);
});

From that iteration you can verify if the key you're exists on the array with keysYouWanToLook.includes(key);

the final code would be something like this:

const keysYouWanToLook = ['a','b'];
const keys = Object.keys(yourObject);
let result = {}
keys.forEach((key, index) => {
  if(keysYouWanToLook.includes(key)){
     result = { ...result, [key]:yourObject[key]}
  }
});
console.log(result);
  • Related