Destructuring array of objects in es6

荒凉一梦 提交于 2021-02-17 12:43:16

问题


In es6, how can i simplify the following lines using destructuring?:

const array0 = someArray[0].data;
const array1 = someArray[1].data;
const array2 = someArray[2].data;

回答1:


Whether using destructuring would actually be a simplification is debatable but this is how it can be done:

const [
  { data: array0 },
  { data: array1 },
  { data: array2 }
] = someArray

Live Example:

const someArray = [
  { data: 1 },
  { data: 2 },
  { data: 3 }
];

const [
  { data: array0 },
  { data: array1 },
  { data: array2 }
] = someArray

console.log(array0, array1, array2);

What is happening is that you're first extracting each object from someArray then destructuring each object by extracting the data property and renaming it:

// these 2 destructuring steps
const [ obj1, obj2, obj3 ] = someArray // step 1
const { data: array0 } = obj1 // step 2
const { data: array1 } = obj2 // step 2
const { data: array2 } = obj3 // step 2

// written together give
const [
  { data: array0 },
  { data: array1 },
  { data: array2 }
] = someArray

Maybe combine destructuring with mapping for (potentially) more readable code:

const [array0, array1, array2] = someArray.map(item => item.data)

Live Example:

const someArray = [
  { data: 1 },
  { data: 2 },
  { data: 3 }
];

const [array0, array1, array2] = someArray.map(item => item.data)

console.log(array0, array1, array2);



回答2:


I believe what you actually want is

const array = someArray.map(x => x.data)

If you really want three variables (Hint: you shouldn't), you can combine that mapping with destructuring:

const [array0, array1, array2] = someArray.map(x => x.data)



回答3:


If you want to do with this pure JS then follow this code snippet. It will help you.

let myArray = [
    {
        "_id": "1",
        "subdata": [
            {
                "subid": "11",
                "name": "A"
            },
            {
                "subid": "12",
                "name": "B"
            }
        ]
    },
    {
        "_id": "2",
        "subdata": [
            {
                "subid": "12",
                "name": "B"
            },
            {
                "subid": "33",
                "name": "E"
            }
        ]
    }
]


const array = myArray.map(x => x.subdata).flat(1)

const isExist = (key,value, a) => {
  return a.find(item => item[key] == value)
}

let a = array.reduce((acc, curr) => {
  if(!isExist('subid', curr.subid, acc)) {
    acc.push(curr)
  }
  return acc
}, [])

console.log(a)



回答4:


const myInfo = someArray.map((item) => {
const {itemval1, itemval2} = item;
return(
   //return data how you want it eg:
   <p>{itemval1}</p>
   <p>{itemval2}</p>)
})

This is how I did it in react, correct me if m wrong, I'm still new to this world



来源:https://stackoverflow.com/questions/49413544/destructuring-array-of-objects-in-es6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!