Issue
I am trying to loop through two API responses. I then want to combine these two results into one array, and then loop through it to get TransactionType
, which is the value that I want. I am quite a noob at looping and it is showing. The API result looks like this:
So far, I've only made it as far as trying to loop through my code,
private async sortTransactiontypes() {
const customTypes = await API(this.params1);
const defaultTypes = await API(this.params2);
const customKey = Object.values(customTypes);
const defaultKey = Object.values(defaultTypes);
for (const key in customKey) {
console.log(JSON.stringify(`${key}: ${customKey[key]}`));
}
}
but I keep getting an "0: [object Object],[object Object],[object Object]" error.
How would I go about in doing what I want to do?
Solution
but I keep getting an "0: [object Object],[object Object],[object Object]" error.
That's not an error. That's the output of console.log
.
You are iterating over the keys of an array, so ${key}
is "0"
.
And [object Object],[object Object]
is how an array of object is implicitly converted to a string.
If you remove the JSON.stringify
and the interpolated string, you should get a better description of what you are logging.
console.log(key, customKey[key])
combine these two results into one array
These appear to be nested arrays, so .flat()
can really help you out here if yo don't care about how they are grouped and just want all the item in each nested array.
const customKey = Object.values(customTypes).flat();
const defaultKey = Object.values(defaultTypes).flat();
Now combine them into one array that contains both with a ...
spread.
const allItems = [...customKey, ...defaultKey];
and then loop through it to get
TransactionType
for (const item of allItems) {
console.log(item.TransactionType);
}
Answered By - Alex Wayne
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.