1

I am new on javascript. What's the best way to extract values of a specific key from list of dictionary without a for loop. For example:

var = [{ name: "Rusty", type: "human", legs: 2, head: 1 },
        { name: "Alex", type: "human", legs: 2, head: 1 },
        { name: "Lassie", type: "dog", legs: 4, head: 1 },
        { name: "Spot", type: "dog", legs: 4, head: 1 },
        { name: "Polly", type: "bird", legs: 2, head: 1 },
        { name: "Fiona", type: "plant", legs: 0, head: 1 }]

I want to extract the values of legs as an array.

var legs = [2,2,4,4,2,0]

Thanks in advance

Bernando Purba
  • 541
  • 2
  • 9
  • 18

1 Answers1

5

You can use map to easily accomplish this:

const dict = [{
    name: "Rusty",
    type: "human",
    legs: 2,
    head: 1
  },
  {
    name: "Alex",
    type: "human",
    legs: 2,
    head: 1
  },
  {
    name: "Lassie",
    type: "dog",
    legs: 4,
    head: 1
  },
  {
    name: "Spot",
    type: "dog",
    legs: 4,
    head: 1
  },
  {
    name: "Polly",
    type: "bird",
    legs: 2,
    head: 1
  },
  {
    name: "Fiona",
    type: "plant",
    legs: 0,
    head: 1
  }
];

let legValues = dict.map(({legs})=>legs);
console.log(legValues);

Hope this helps,

Miroslav Glamuzina
  • 4,472
  • 2
  • 19
  • 33
  • What is ({legs}) doing? I get that "legs" is the key but there is some js notation that is hard to google search without knowing what its called. – mathtick Jun 04 '21 at 11:01
  • 1
    @mathtick sorry for the late response, the notation you see there with `{legs}` is called object destructuring. Here's a comprehensive guide from MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment – Miroslav Glamuzina Sep 23 '21 at 05:31