I have an object of objects as below
data = {
Sam: { details: [ /* array items */ ] },
Jill: { details: [ /* array items */ ] },
Bill: { details: [ /* array items */ ] },
}
Then I have the code below to filter the data based on the name
filteredData = {};
Object.keys(data).forEach((name) => {
filteredData[name] = data[name];
});
I call this in a constructor as below to get the details of the particular name
vis.dataFilteredTemp = filteredData[vis.name];
vis.dataFiltered = vis.dataFilteredTemp["details"];
if vis.name is Jill, then the output is {details: Array(3)} & this works just fine.
Now, I want the details of all names with is filteredData method. How can I do it?
The out put expected is {details: Array(13)}} if I do vis.dataFilteredTemp = filteredData[] (empty array is passed). 13 arrays because arrays of all names are added up.
Since I am working with d3.csv, I am unable to pass the data directly to the constructor. Can any one help?
Iterate over the Object.values, and use flatMap to merge each array's details.
const data = {
Sam: { details: [1,2,3,4]},
Jill: { details: [4,5,6] },
Bill: { details: [7,8,9,10,11,12] }
};
function getData(data, name = '') {
if (name) return { details: data[name].details };
return { details: Object.values(data).flatMap(arr => arr.details) };
}
console.log(getData(data));
console.log(getData(data, 'Jill'));
If I understand well, you should use Array.reduce
const data = {
Sam: { details: [1,2] },
jenn: { details: [3,4] },
kurt: { details: [6, 9 , 10, 16] }
};
const result = Object.values(data).reduce((acc = {details: []}, val) => {
acc.details.push(...val.details);
return acc;
});
console.log(result.details);
outputs : [1, 2, 3, 4, 6, 9, 10, 16]