I am using node js and fetching data from a url that returns a list of 28000+ JSON objects. I want to map each objects identifier to one of its sub-objects. Every example of mapping in JS I look at is expecting the JSON to be in a key value format like "id:value"
The JSON data im getting is
'28338': {
high: 696000000,
highTime: 1691191991,
low: 672500000,
lowTime: 1691190341
}
I want to create a map of 28338:high.
Every top level field (28338) is uniquely named so I cant just say map ID:high since that field isnt called ID. Its called 28338. And on item id 28337 the field is called 28337 etc. 1-28000+ So Id need to map 28000+ times.
My end goal is to fetch the latest item prices from the URL and then create a map of them like 28338:696000000 so I can later loop through it and update a sqlite db. update items SET itemValue = ? where itemID = ?
(high,28338).
But right now I cant even build the map of objects.
async function getData() {
const url = 'https://prices.runescape.wiki/api/v1/osrs/latest';
const response = await fetch(url);
const jsonResponse = await response.json();
console.log(jsonResponse);
return Object.keys(jsonResponse).reduce((result, key) => {
result[key] = jsonResponse[key].high;
return result;
}, {})
}
const myList = await getData();
When I test this in a console and I console.log(myList) it returns { data: undefined }
3
Answers
You can use
Object.entries()
andreduce()
to achieve what you want:The idea is simple: You can get an array of arrays which contain key-value pairs using
Object.entries()
, then you just have to build up a new object with thekey
and thehigh
property of thevalue
.The callback
reduce()
has two relevant arguments for us here. The aggregated value (hereagg
) and the current value of the iteration. For the current value we use quite a bit of descructuring. We know we get an array like this fromObject.entries()
[key, value]
so we can destructure like this right away, so we already have thekey
of our new object. Additionally we also need thehigh
property value from thevalue
. We know value looks like this:So we can just use object destructuring to obtain the one value we’re interested in like this
{ high }
.The rest is straightforward: we assign the
key
with the valuehigh
to our new objectagg
and returnagg
so it can be passed to us again in the next iteration. In the end we’ll end up with the expected result.Of course you do not have to use destructuring or just some. So the callback in
reduce()
could also look like this (all are identical in functionality):Your response has the data of interest in a
data
property. So you need to get the key/values from that property.NB: I prefer using
Object.fromEntries
in place ofreduce
, but it is not essential:A simple way to do this is to aggregate into a new json and return it.