Lenn
Lenn

Reputation: 1479

Destructure array of objects with renaming

I know this is a more than easy question and many similar ones exist here, but I couldn't find a quick solution.

So I just want to create a variable called age2 that holds the value of Mikes age, so 29.

let arr = [
  {
    "name": "Mike",
    "age": 29
  },
  {
    "name": "Michael",
    "age": 24
  }
]

I thought this should work:

let [first: {age: age2}] = arr

To first get the first element and then destructure the object, but it says:

Uncaught SyntaxError: missing ] after element list

Upvotes: 0

Views: 297

Answers (2)

Codebling
Codebling

Reputation: 11382

Selecting elements of an array isn't part of destructuring syntax, it's part of basic Javascript syntax.

You could use array destructuring, but it gets unwieldy if you need more than one:

let [{age: age2}] = arr; //first element
let [{age: age2}, {age: age3}, {age: age4}] = arr; //more...

You could also specify the element you want to destructure:

const {age: age2} = arr[0];

Or you could remap the whole array to be in that format:

const people = arr.map(({name, age:age2}) => ({name, age2}));

Upvotes: 1

Daniel Black
Daniel Black

Reputation: 605

You can use the find method to get the 'Mike' object, then pull the age:

let arr = [
  {
    "name": "Mike",
    "age": 29
  },
  {
    "name": "Michael",
    "age": 24
  }
]

let age2 = arr.find(function(element){return element.name == "Mike"}).age

console.log(age2)

Upvotes: 1

Related Questions