How can I loop through arrays inside an object in JavaScript es6? I tried the following code
for(let x of Object.keys(headings?.value)){
console.log(x);
}
data i wants to loop through
"value":{
"h3":[
"Best selling products",
"Best Corporate Laptops",
"BEST PRICED LAPTOPS",
"Shop By Brands"
],
"h4":[
"Lenovo Thinkpad Touchscreen Yoga X380/i5/8th gen/13.3" screen",
"Lenovo thinkpad T440S/core i7/4th gen/14"screen"
],
"h5":[
"View All",
]
}
3
Answers
This code will print the keys (h3, h4, h5) along with their corresponding items in the console. If data is a JSON string, you need to parse it into an object using JSON.parse() before using the code below.
Now that you know each key, you just need to access the values of the object.
Alternatively, you can use
Object.values()
if you don’t care about the keysIn JavaScript ES6, you can use the Object.entries() method to get both the keys and values of the object. Then, you can iterate through each array using a nested loop. Here’s how you can do it: