Reputation: 79
I am trying to split
const alreadyParsed = {"data":[{"name":"foo", "value":"bar"},{"name":"chicken", "value":"nugget"}]}
into
const headers = ["name","value"]
and
const datas = [ ["foo","bar"],["chicken","nugget"] ]
hopefully, using
const headers = alreadyParsed.map(?)
const datas = alreadyParsed.map(?)
not sure what I should be googling to figure this out / what options are available.
Upvotes: 1
Views: 88
Reputation: 599
This is assuming that all objects in your initial data array are going to have the same keys (name, value).
// your initial object
const alreadyParsed = {"data":[{"name":"foo", "value":"bar"},{"name":"chicken", "value":"nugget"}]}
// get the values inside the objects 'data' key
var dataArray = alreadyParsed.data;
// get the objects keys (this is where we assume all index keys are the same as index 0).
var keyArray = Object.keys(this.dataArray[0]);
// build an array of the objects values.
var valuesArray = [];
for (var item of this.dataArray){
valuesArray.push(Object.values(item);
}
console.log("--Key Array--");
console.log(keyArray );
console.log("--ValueArray--");
console.log(valuesArray );
Definitely better off using .map as seen above. :p
Upvotes: 0
Reputation: 6516
Assuming you know that every data object will have the same keys, you can use Object.keys()
for your first need, the headers
.
And for the values (your datas
variable), you can use the .map
that you were thinking to use, mixed with Object.values()
(If your keys for headers
are not always the same, then use the same logic above, used for getting datas
)
Below you can see this idea in the working snippet:
const alreadyParsed = {"data":[{"name":"foo", "value":"bar"},{"name":"chicken", "value":"nugget"}]}
const headers = Object.keys(alreadyParsed.data[0])
const datas = alreadyParsed.data.map(x => Object.values(x))
console.log(headers)
console.log(datas)
Further reading about Object methods.
Upvotes: 5