Reputation: 1135
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
Upvotes: 2
Views: 13052
Reputation: 694
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
Upvotes: 0
Reputation: 73241
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);
Upvotes: 2
Reputation: 104775
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/
Upvotes: 7