Reputation: 707
I would like to obtain array in object within array.
Original structure:
Array [ object, ..., object ]
var dateC = [
{
key: "2016-01-01",
values: **[
{city:"", country:""...},
{...}
]**},
{
key: "2016-01-02",
values: [
{...},
{...}
]}
]
var dateC2 = dateC.filter(function(d) { return d.key == selected; }).map(function(d) { return d.values })
I extracted the object from dateC that has key: "2016-01-01" using the above code.
Current structure:
Array [ Array[114] ]
var dateC2 = [
{
key: "2016-01-01",
values: **[
{city:"", country:""...},
{...}
]**}
]
Desired structure:
Array [ Object, ..., Object ]
**[{city:"", country:""...}, {...}]**
Array that I want is contained by **
I am not sure how I should use forEach method to get the array from values because I have already use filter and map on dateC to obtain dateC2. Alternatively, is there a quicker way to obtain the desired structure from original structure?
Upvotes: 1
Views: 858
Reputation: 3536
I think Array.prototype.forEach
would be another choice:
var dateC2 = [];
dateC.forEach(function(d) {
if(d.key == selected)
dateC2 = dateC2.concat(d.values);
});
Or
var dateC2 = [];
dateC.forEach(function(d) {
if(d.key == selected)
Array.prototype.push.apply(dateC2, d.values);
});
Upvotes: 1
Reputation: 386654
You could use a single loop for it with Array#reduce
.
var dateC2 = dateC.reduce(function(r, d) {
return d.key == selected ?
r.concat(d.values):
r;
}, []);
Upvotes: 4