Consider having a json object we want to convert
const my_object = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
There is several solution you can use :
1. Object.keys() and Object.values()
Theses functions convert any object to an array. One returns an array with all the keys, and the other all the values :
console.log(Object.keys(my_object))
// Output : ["key1", "key2", "key3"]
console.log(Object.values(my_object))
// Output : ["value1", "value2", "value3"]
I'm not sure to understand the initial question, but the solution would probably be
data.addRows(Object.values(my_object));
2. Object.entries()
This function is a mix of the two above:
console.log(Object.entries(my_object))
// Output : [["key1", "value1"], ["key2", "value2"], ["key3", "value3"]]
It no use for the initial question, but this function is so usefull I had to mention it. Especially, when the value_ are nested object.
Let say our values are objects like this :
const my_object = {
"key1": {"a": 1, "b": 2},
"key2": {"y": 25, "z": 26},
"key3": {"much": "stuff"}
}
and we want to end up with an array like this
my_array = [
{"key": "key1", "a": 1, "b": 2},
{"key": "key2", "y": 25, "z": 26},
{"key": "key3", "much": "stuff"}
]
We need to use Object.entries()
to get all our key with their value. We will start with an overdetailed code :
my_array = Object.entries(my_object).map(function(entry){
key = entry[0];
value = entry[1];
nested_object = value;
nested_object.key = key;
return nested_object;
});
console.log(my_array);
// Expected output : [
// {"key": "key1", "a": 1, "b": 2},
// {"key": "key2", "y": 25, "z": 26},
// {"key": "key3", "much": "stuff"}
//]
We can make use of spread operator to simplify our code :
my_array = Object.entries(my_object).map(entry => {"key": entry[0], ...entry[1]});
console.log(my_array);
// Expected output : [
// {"key": "key1", "a": 1, "b": 2},
// {"key": "key2", "y": 25, "z": 26},
// {"key": "key3", "much": "stuff"}
//]