1

I have my original objects as follow. All I need is to just extract few properties from existing one and create new object.

var data = [{
    id: 3,
    name: Axe,
    location: alkt
}, {
    id: 5,
    name: Roy,
    location: grelad
}]

I need my output as,

var data_new = [{
    id: 3,
    name: Axe
}, {
    id: 5,
    name: Roy,
}]

How to implement in underscore js or any simple method. Possible its a large JSON object.

5 Answers 5

4

If there are just few properties you want to extract then simple Array.prototype.map will works fine:

var data = [{
    id: 3,
    name: 'Axe',
    location: 'alkt'
}, {
    id: 5,
    name: 'Roy',
    location: 'grelad'
}]

var result = data.map(function(obj) {
    return {
      id: obj.id,
      name: obj.name
    };
});

alert(JSON.stringify(result, null, 4));

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

4 Comments

It has to be noted that this will not work in IE8 as it does not support Array.prototype.map.
Yes, if IE8 is supported then data.map(function(obj) {}) should be changed to _.map(data, function(obj) {}). Thanks for the note!
So you suggest if a browser only supports ECMA-Script 3 to use a full-blown library? I mean, we all love underscore.js, but why not just go with a standard approach of a for loop using for..in inside?
I assume that OP is already using underscore, so why not use it if IE8 support is necessary. If IE8 is not important then use ES5 map.
2

Use pick in undescorejs http://underscorejs.org/#pick Or omit http://underscorejs.org/#omit

_.pick({name: 'moe', age: 50, userid: 'moe1'}, 'name', 'age');
=> {name: 'moe', age: 50}
_.pick({name: 'moe', age: 50, userid: 'moe1'}, function(value, key, object) {
  return _.isNumber(value);
});
=> {age: 50}

Comments

1

It you want remove each item's location

var data_new = _.map(data, function(item) {
  return _.omit(item, 'location');
});

Comments

0

If all you want is remove properties from objects in an array, you could just delete them while iterating with forEach:

var data_new = data;
data_new.forEach(function(obj){ delete obj.location; /* or any other */ });

2 Comments

forEach is not supported in IE8. Also, OP is asking for a new object, not how to alter the original one.
There was no premise it had to work in a 4½ year old IE. My link even comprises a polyfill at MDN. An edited copy of the original object ''is'' a new object.
0
$scope.data_new = [];
for(i in $scope.data){
  $scope.data_new.push(
   { id: $scope.data[i].id, name: $scope.data[i].name }
  )
}

1 Comment

I'd recommend not to use for ... in for arrays.

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.