1

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?

1
  • please add some more data, especially how the result should look like. Commented Jul 4, 2016 at 8:09

2 Answers 2

4

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;
}, []);
Sign up to request clarification or add additional context in comments.

1 Comment

I think forEach would be a better choice. (as you mentioned before, no need to return).
1

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);
});

2 Comments

Hi, why is it better? Is it because it has a better performance?
@Shawn If this comment is about my comment under Nina's answer, yes. But you should ask it there not here.

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.