gkeenley
gkeenley

Reputation: 7388

Javascript: Is there a cleaner way to extract object properties?

I have the following JS code:

let obj1 = {
    prop1: 1,
    prop2: 2,
    prop3: 3,
    prop4: 4
}

let obj2 = {
    prop1: obj1.prop1,
    prop2: obj1.prop2,
}

Here I create obj2 which has certain select properties of obj1. Is there a cleaner/quicker way to do this than what I've done here? Some kind of destructuring hack?

Upvotes: 2

Views: 1307

Answers (5)

Divyansh Yadav
Divyansh Yadav

Reputation: 51

let obj1 = {
    prop1: 1,
    prop2: 2,
    prop3: 3,
    prop4: 4
}

let { prop1, prop2 } = obj1

let obj2 = {
    prop1,
    prop2
}

console.log(obj2)

Upvotes: 1

chiragrtr
chiragrtr

Reputation: 932

JSON.stringify way is great except that won't work for functions. So, if you have function in your object, better to do this:

let obj1 = {
    prop1: function(x){console.log("hello", x)},
    prop2: 2,
    prop3: 3,
    prop4: 4
}

const keysForObj2 = ["prop1", "prop2"]

let obj2 = {};

for (key in obj1) {
    if (keysForObj2.includes(key)) {
        obj2[key] = obj1[key];
    }
}
console.log(obj2);    // Only prop2 will be present with JSON way

obj2.prop1("world"); You can't do this in JSON way

Upvotes: 0

richytong
richytong

Reputation: 2462

You could get do it with a utility function I created.

let obj1 = {
  prop1: 1,
  prop2: 2,
  prop3: 3,
  prop4: 4
}

const { pick } = rubico

const obj2 = pick(['prop1', 'prop2'])(obj1)

console.log(obj2)
<script src="https://unpkg.com/rubico/index.js"></script>

Documentation for pick

Upvotes: 0

Nilesh Chavan
Nilesh Chavan

Reputation: 381

Hi try to store all your obj1 properties to obj2. may e it will help you.

let obj1 = {
    prop1: 1,
    prop2: 2,
    prop3: 3,
    prop4: 4
}
//ES6
let obj2 = {}
for(key in obj1){
  obj2[key]= obj1[key]
}
console.log(obj2)
//ES5
let obj3 = {}
Object.keys(obj1).forEach(function(key){
  obj3[key]= obj1[key]
})
console.log(obj2)

Upvotes: 0

Narendra Chouhan
Narendra Chouhan

Reputation: 2319

You can do this way,

let obj1 = {
    prop1: 1,
    prop2: 2,
    prop3: 3,
    prop4: 4
}

let obj2 = JSON.parse(JSON.stringify(obj1,['prop1','prop2']))
console.log(obj2)

Upvotes: 2

Related Questions