how to destructure a json array of objects in Javascript

问题: I have an object "data" from 'https://randomuser.me/api/' which I'm using in my project. { "results": [ { "gender": "female", "name": { "title":...

问题:

I have an object "data" from 'https://randomuser.me/api/' which I'm using in my project.

{
  "results": [
    {
      "gender": "female",
      "name": {
        "title": "miss",
        "first": "mia",
        "last": "sutton"
      }
    }
  ]
}

I destructured results from the data object as follows; const {results} = data; How do I destructure the results variable I created, and obtain the first item from it I want the de-structured array item to be declared as profile. This represents the profile data for the user gotten from the API call that I want to display in my app.


回答1:

You can do it like this:

const { results: [firstItem] } = data;

See this MDN article for more info on destructuring.

const data = {
  "results": [
    {
      "gender": "female",
      "name": {
        "title": "miss",
        "first": "mia",
        "last": "sutton"
      }
    }
  ]
};

// declare a const variable named firstItem that holds the first element of the array
const { results: [firstItem] } = data;
// You could event destructure the content of this first array item like this
const { results: [{ gender, name }] } = data;
// or go deeper like this
const { results: [{ name: { title, first, last } }] } = data;

console.log(firstItem);
console.log(gender);
console.log(name);
console.log(title, first, last);

According to your code (see comments), this should work too:

const data = {
  "results": [
    {
      "gender": "female",
      "name": {
        "title": "miss",
        "first": "mia",
        "last": "sutton"
      }
    }
  ]
};

const displayUserPhotoAndName = (data) => {
  if(!data) return;
  const { results } = data;
  const { results: [profile] } = data;

  console.log(profile);
}

displayUserPhotoAndName(data);

  • 发表于 2019-03-15 14:01
  • 阅读 ( 184 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除