2

I am trying to concat a multidimensional array so I can iterate and display all the data. There is a very good post on how to access nested data here, but I am looking for a solution that works with a specific data structure.

Here is my data:

var data = {
"Nike": [
    {
    "id": "1",
    "name": "test",
    "myimage": "image.gif"},

     {
    "id": "2",
    "name": "test",
    "myimage": "image.gif"}
],

"Adidas": [
    {
    "id": "3",
    "name": "Football Boots",
    "myimage": "image.gif"},

     {
    "id": "4",
    "name": "Running Shoes",
    "myimage": "image.gif"}
]}

I seem to be able to get the values from the Nike array if I do this:

var result = data.Adidas;


for (var i = 0; i < result.length; i++) {
 var object = result[i];
 for (property in object) {
    var value = object[property];
    alert(property + "=" + value + "<br>");
 }
}

However I would like to be able to display all the array items (id's 1-4).

What I have tried to do is:

var result = [].concat.apply([], data);

... and loop over the result variable using the same for loop, but it doesn't work.

My ideal end result would be to display the four products under each brand name. I don't require to show the actual brand name itself. For example:

 "id": "1",
    "name": "test",
    "myimage": "image.gif"

 "id": "2",
    "name": "test",
    "myimage": "image.gif"

"id": "3",
    "name": "Football Boots",
    "myimage": "image.gif",

"id": "4",
    "name": "Running Shoes",
    "myimage": "image.gif"

Any help appreciated.

Cheers

1

3 Answers 3

7

You can use reduce and iterate over the keys of the object, then create your array:

var mashed = Object.keys(data).reduce(function(arr, key) {
    return arr.concat(data[key]);
}, []);

Demo: https://jsfiddle.net/kvd6egn5/

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

1 Comment

Perfect!! Does exactly what I am looking for. Thanks so much tymeJV
2

An alternative to reduce would be a for in loop:

let res = [];
for (let key in data) res = res.concat(data[key]);
console.log(res);

Comments

0

You can use the lodash mergeWith function:

const object = {
  'a': [{ 'b': 2 }, { 'd': 4 }]
};

const other = {
  'a': [{ 'c': 3 }, { 'e': 5 }]
};

_.merge(object, other);

https://lodash.com/docs/4.17.15#mergeWith

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.