Reputation: 1075
I would like to use forEach
in JavaScript.
sentence.forEach(function(value) {--------
When sentence
is an array, forEach works properly.
{
"sentence": [
{
"word": [
{
"content": "tell"
},
{
"content": "me"
}
]
},
{
"word": [
{
"content": "do"
},
{
"content": "you"
},
{
"content": "want"
}
]
}
]
}
However, when sentence
has only one value and is not an array, forEach doesn't work and it makes error message like this. Uncaught TypeError: sentence.forEach is not a function
{
"sentence": {
"word": {
"content": "hello"
}
}
}
I get json object from external API, so I don't know whether sentence
has only one value or many values. How can I solve this problem? Could you give me any information or advice?
Upvotes: 1
Views: 228
Reputation: 386654
You could convert the data to an array with Array#concat
if it is no array or keep the array.
[].concat(data).forEach(callback);
For using this approach, you could wrap it in a function getArray
.
const
getArray = value => [].concat(value),
callback = ({ word }) =>
getArray(word).forEach(({ content }) => console.log(content)),
a = { sentence: [{ word: [{ content: "tell" }, { content: "me" }] }, { word: [{ content: "do" }, { content: "you" }, { content: "want" }] }] },
b = { sentence: { word: { content: "hello" } } };
getArray(a.sentence).forEach(callback);
getArray(b.sentence).forEach(callback);
Upvotes: 4
Reputation: 2422
Split your code conditionally
if(Array.isArray(sentence)
{
//your foreach
}
else
{
//pick relevant properties from sentence object
}
Upvotes: 1
Reputation: 4176
Make sure you always have an array, and convert it to an array if it isn't. You could do something like the following:
const sentenceArray = Array.isArray(sentence) ? sentence : [sentence];
Then use sentenceArray instead like so:
sentenceArray.forEach(...
Upvotes: 6