I am trying to create a new array out of limited values from an existing array. In the example below LargeArray
contains many attributes – year, books, gdp and control. Lets say I want to create a new array that would only include year and gdp.
var LargeArray = [
{year:1234, books:1200, gdp:1200, control:1200},
{year:1235, books:1201, gdp:1200, control:1200},
{year:1236, books:1202, gdp:1200, control:1200}
];
The new array I am trying to get, would look like this:
var NewArray = [
{year:1234, gdp:1200},
{year:1235, gdp:1200},
{year:1236, gdp:1200}
];
I am trying to create a new array out of limited values from an existing array. In the example below LargeArray
contains many attributes – year, books, gdp and control. Lets say I want to create a new array that would only include year and gdp.
var LargeArray = [
{year:1234, books:1200, gdp:1200, control:1200},
{year:1235, books:1201, gdp:1200, control:1200},
{year:1236, books:1202, gdp:1200, control:1200}
];
The new array I am trying to get, would look like this:
var NewArray = [
{year:1234, gdp:1200},
{year:1235, gdp:1200},
{year:1236, gdp:1200}
];
Share
Improve this question
edited Sep 4, 2013 at 5:16
Felix Kling
817k181 gold badges1.1k silver badges1.2k bronze badges
asked Sep 4, 2013 at 5:03
Rohan SandeepRohan Sandeep
4141 gold badge7 silver badges15 bronze badges
1
- I would like to use Jquery to create the new array, i am not sure if map function would help. If it's better with plain javaScript its great too. – Rohan Sandeep Commented Sep 4, 2013 at 5:05
2 Answers
Reset to default 5use $.map()
var LargeArray = [{year:1234, books:1200, gdp:1200, control:1200}, {year:1235, books:1201, gdp:1200, control:1200}, {year:1236, books:1202, gdp:1200, control:1200}, {year:1237, books:1203, gdp:1200, control:1200}, {year:1238, books:1204, gdp:1200, control:1200}];
var NewArray = $.map(LargeArray, function (value) {
return {
year: value.year,
gdp: value.gdp
}
})
Demo: Fiddle
Using Array.prototype.map
var newArray = largeArray.map(function(obj) {
return { year: obj.year, gdp: obj.gdp };
});
Note: Array.prototype.map
is a recent addition. Use the shim from MDN to support older browsers.
jsFiddle Demo