1

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?

2
  • For your object, shallow copying will be enough, but incase if you do have reference type data fields as well, you can use const cpy = JSON.parse(JSON.stringify(obj)) or const cpy = cloneDeep(obj). cloneDeep is a method from lodash Commented Jun 21, 2022 at 14:23
  • Please provide a minimal reproducible example that demonstrates your need and desired output... if you want a deep clone then at least one example input should be a nested object. And what kinds of properties will the object have? Will there be arrays? functions? circular references? Edge cases tend to drive implementations, so you should consider what you want to see happen and ask for that in advance, rather than get an answer that works for the simple case above but fails for your actual use case. Commented Jun 21, 2022 at 18:52

3 Answers 3

1
// By defining Keys as keys of T, you get autocompletion
// Also by setting mapped type as return you only get 
// the props you have copied in the return
const getSubset = <T, Keys extends keyof T, SubSet extends { [K in Keys]: T[K] }>(
  obj: T,
  keys: Keys[]
): SubSet => {
  return keys.reduce((acc, key) => ({ [key]: obj[key], ...acc }), <SubSet>{});
};

const object = { bio: { name: "James", age: 23 }, hobbies: ["Fishing", "Hunting", "Coding"] };
// now copy will only show you bio and not hobbies
const copy = getSubset(object, ["bio"]);
// you can mutate 
copy.bio = { name: "Jill", age: 33 };

// and it does not have side effect on original object
console.log(copy.bio, object.bio);
// prints: {name: 'Jill', age: 33} {name: 'James', age: 23}
Sign up to request clarification or add additional context in comments.

Comments

1

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


4 Comments

Hi. Thanks for response. But in this case it would be a shallow copy right?
@Hayk It's fully a new object. So if you do any change in the copy object like copyObj.d=6, it won't effect the main obj.
Thanks again for your time. I refer to cases when object contains objects or arays itself. For instance if you have const object = {bio: {name: "James", age: 23}, hobbies: ["Fishing", "Hunting", "Coding"]} Even after copying, if i change copyObj.bio.name, it will be changed in the original array as well.
@Hayk In that case you can use external library like loadash. I think you are looking for something like loadash._omit method. Check this out google.com/amp/s/www.geeksforgeeks.org/lodash-_-omit-method/amp
1

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

4 Comments

Hi. Thanks for response. But is it not a shallow copy?
I don´t get what dou you mean by shallow copy, you mean pointer wise?
Yes, pretty much
Just add the spread operator on the [key]: ...yourObject[key] line, it should work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.