0

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",
           
        ]
     }
2
  • 2
    Use Object.values().flat() instead of Object.keys(). Also, you don't need ?.; just use headings.value. If headings is nullish Object.keys()/.values() will throw an error anyway. Commented Jul 28, 2023 at 14:24
  • 1
    Does this answer your question? Iterate through object values - javascript Commented Jul 28, 2023 at 14:26

1 Answer 1

1

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 keys

const headings = {
  "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",

      ]
   }
 };

console.log("KEY/VALUE PAIRS");
for(let key of Object.keys(headings.value)){
  const val = headings.value[key];
  console.log(key, val);
}

console.log("VALUES ONLY");
for(let val of Object.values(headings.value)){
  console.log(val);
}

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.