Codiqo

Learn JavaScript · lesson 30 of 60 · about 8 minutes

Nested Data

Show Sam's posts: combine arrays and objects to model real data, and loop over keys and entries.

What you'll learn

  • Read nested arrays and objects
  • Loop with Object.keys and Object.entries
  • Choose a shape for data

Sam's posts

Sam has written a few posts, and each one is more than a single value: it has a title, a number of likes and some tags. So each post is an object, and the posts together are an array of objects, posts, oldest first. The page adds up all the likes, and shows the newest post's title and its first tag, newest.tags[0].

Data inside data

Real data mixes arrays and objects: a list of users, each with a list of badges. Chain lookups from left to right:

users[0].badges[1] means "first user, their badges, the second one".

A list of objects

const users = [
  { name: "Ada", badges: ["streak", "perfect"] },
  { name: "Bo", badges: ["first-lesson", "night-owl"] },
];
console.log(users[0].badges[1]);
console.log(users[1].name);
for (const u of users) {
  console.log(`${u.name}: ${u.badges.length} badges`);
}

Output

perfect
Bo
Ada: 2 badges
Bo: 2 badges

Looping over an object

Object.keys(obj) gives an array of keys, Object.values(obj) the values, and Object.entries(obj) gives [key, value] pairs.

entries

const xp = { python: 120, javascript: 80 };
for (const [lang, points] of Object.entries(xp)) {
  console.log(lang, points);
}
console.log(Object.keys(xp).length);

Output

python 120
javascript 80
2

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.