0

I've got this object:

var obj = {
    name : 'Allen',
    last : 'Jones',
    age : 24,
    city : 'London'
}

and this array : ['name', 'age', 'city']

What is the most efficient way to create an object from that selected fields? Such as below, without to delete the properties of the first one?

obj2 = {name: 'allen', age: 24, city: 'London'}
2

6 Answers 6

3

I suggest to use a Array#forEach() and iterate over the given keys for the new object.

var obj = { name: 'Allen', last: 'Jones', age: 24, city: 'London' },
    array = ['name', 'age', 'city'],
    obj2 = {};

array.forEach(function (a) {
    obj2[a] = obj[a];
});

document.write('<pre>' + JSON.stringify(obj2, 0, 4) + '</pre>');

Sign up to request clarification or add additional context in comments.

Comments

1

try this simple loop

var obj = {
    name : 'Allen',
    last : 'Jones',
    age : 24,
    city : 'London'
};
var obj2 = {};
var arr = ['name','age','city'];
arr.forEach(function(val){
   obj2[val] = obj[val]; 
});

now obj2 should have only selected properties

Comments

0

You may use a loop to iterate through each property. There are many approaches for that, such as for loops, while loops or foreach loops. Here's one, using a simple for loop:

var obj = {
  name: 'Allen',
  last: 'Jones',
  age: 24,
  city: 'London'
};

var arr = ['name', 'age', 'city'];
var obj2 = {};

for (var i = 0; i < arr.length; i++) {
  var property = arr[i];
  obj2[property] = obj[property];
}

Live example can be seen here.

Comments

0

You can delete 'last' property from existing object and the object will be same as you want.

 var obj = {
              name : 'Allen',
              last : 'Jones',
              age : 24,
              city : 'London'
           }

 delete obj.last;

 console.log(obj);

Hope this help.

Comments

0

Below is a general purpose method with your desired output:

var obj = {
    name : 'Allen',
    last : 'Jones',
    age : 24,
    city : 'London'
};

obj2 = ['name', 'age', 'city'];

function createObject(obj, arr) {
    var newObj = {};
  
    arr.forEach(function(value) {
        if(obj.hasOwnProperty(value)) {
            newObj[value] = obj[value];
        }
    });
  
    return newObj;
}

document.write(JSON.stringify(createObject(obj, obj2)));

Comments

0

There are many nice ways shown under this answer. This is a functional chainable method.

var obj = {
           name : 'Allen',
           last : 'Jones',
            age : 24,
           city : 'London'
          },
    arr = ['name', 'age', 'city'],
    res = arr.reduce((p,c) => {p[c] = obj[c]; return p} ,{});

document.write("<pre>" + JSON.stringify(res) + "</pre>");

Comments

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.