JoeVegaCoding
JoeVegaCoding

Reputation: 53

How Do I grab values from multiple object in a JSON format and store them in an array?

I have an array of objects in a JSON format:

[
  {
    "word": "turkey"
  },
  {
    "word": "tiger"
  },
  {
    "word": "horse"
  },
  {
    "word": "pig"
  },
  {
    "word": "dog"
  },
  {
    "word": "cat"
  }
]

I want to extract the value for each "word" key and store it into an array like so:

let wordsArray = ["turkey", "tiger", "horse", "pig", "dog", "cat"];

Upvotes: 1

Views: 49

Answers (2)

Spectric
Spectric

Reputation: 31992

You can use Array.map to extract the value of the word property:

const arr = [
  {
    "word": "turkey"
  },
  {
    "word": "tiger"
  },
  {
    "word": "horse"
  },
  {
    "word": "pig"
  },
  {
    "word": "dog"
  },
  {
    "word": "cat"
  }
]

const res = arr.map(e => e.word);
console.log(res);

Upvotes: 1

Alberto
Alberto

Reputation: 12939

You just need to map the values:

console.log([
  {
    "word": "turkey"
  },
  {
    "word": "tiger"
  },
  {
    "word": "horse"
  },
  {
    "word": "pig"
  },
  {
    "word": "dog"
  },
  {
    "word": "cat"
  }
].map( ({word}) => word ))

Upvotes: 1

Related Questions