'How can I pull all values of a repeating key from a JSON object?
So I am currently querying a huge list of Json Objects (2,000 to be exact). Within the query or URI I am using it pulls thousands of objects that share the same key values. How do you pull all of the values from one specific key? So If I want to pull all the "id": values and log those, how do I do that?
The other problem I have is the object obviously maintains no specific order and the values of those keys are constantly changing, so using dot notation to parse through an array doesn't really work. Here is my example code.
function myFunction() {
var res = UrlFetchApp.fetch("API QUERY")
var content = res.getContentText();
var json = JSON.parse(content);
var jobId = json["items"][0]["name"]
var values = Object.keys(jobId).map(function (key) { return jobId[key]; });
Logger.log(values)
};
The response looks like this:
{
"items": [
{
"id": ,
"name": "My job name",
"status": "open",
"created": 153173990000,
"finished": 153174000000,
"tracking": "https://api/not-a-real-tracking-link",
"group": 6417500000,
"site": {},
"progress": 0,
}
]
}
And then it repeats 2000 times on after the other
{
"items": [
{
"id": ,
"name": "My job name2",
"status": "open",
"created": 153173990000,
"finished": 153174000000,
"tracking": "https://api/not-a-real-tracking-link",
"group": 6417500000,
"site": {},
"progress": 0,
}
]
}
{
"items": [
{
"id": ,
"name": "My job name3",
"status": "open",
"created": 153173990000,
"finished": 153174000000,
"tracking": "https://api/not-a-real-tracking-link",
"group": 6417500000,
"site": {},
"progress": 0,
}
]
}
So the query itself pulls 2000 objects just like this, I need the pull the values of the "name" key from each object and log them.
Solution 1:[1]
You can use Array.reduce() to stack values into a new object:
const json = [
{id: 123, value:"val a"},
{id: 124, value:"val b"},
{id: 125, value:"val c"},
{id: 123, value:"val d"},
{id: 125, value:"val e"},
{id: 223, value:"val f"},
{id: 123, value:"val g"},
{id: 123, value:"val h"},
{id: 123, value:"val i"},
{id: 223, value:"val j"},
{id: 223, value:"val k"},
];
console.log( json.reduce( (newObj, data) =>
{
const array = newObj[data.id] = newObj[data.id] || []; //get already existing array or create a new one
array[array.length] = data.value; //append value to the end of the array
return newObj;
}, {} /* init newObj as empty object */ ));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | vanowm |
