首页 > javascript > 将对象数组中的对象转换为数组,同时保留其他数据

将对象数组中的对象转换为数组,同时保留其他数据 (Converting an object in an array of objects into an array, while preserving other data)

问题

我有以下对象数组:

const datasubject = 
[
 0: {
    level: "standard 3"
    subject: "English"
    _id: xxx
    coreCompetencies {
       0gHq0U5E667L4EdGbdZ2h: "Grammar",
       9CfalSpzKYIV7AaWKBUwg: "Listening",
       9boIfWUEGdj3WGxJL12XB: "Reading",
       QZ11uYQ8CXkRk0LWenjqj: "Writing",
       ZG1gtxRg6quIOYaTr6CUy: "Speaking"
    }
 },
 1: {...},
 2: {...}
]

我想将其更改coreCompetencies为值数组,例如["Grammar", "Listening", "Reading", "Writing", "Speaking"]在保留其他数据时。我试过.map但感到困惑,因为它只返回coreCompetencies对象,没有其他细节。这就是我所做的只返回coreCompetencies对象:

const datacore = datasubject.map(value => value.coreCompetencies);

我想实现这样的目标:

const datasubject = 
[
 0: {
    level: "standard 3"
    subject: "English"
    _id: xxx
    coreCompetencies ["Grammar","Listening","Reading","Writing","Speaking"]
 },
 1: {...},
 2: {...}
]

解决方法

const datacore = datasubject.map(({coreCompetencies, ...rest})=> {
  return {...rest, coreCompetencies: Object.values(coreCompetencies)}
})

问题

I have the following array of objects:

const datasubject = 
[
 0: {
    level: "standard 3"
    subject: "English"
    _id: xxx
    coreCompetencies {
       0gHq0U5E667L4EdGbdZ2h: "Grammar",
       9CfalSpzKYIV7AaWKBUwg: "Listening",
       9boIfWUEGdj3WGxJL12XB: "Reading",
       QZ11uYQ8CXkRk0LWenjqj: "Writing",
       ZG1gtxRg6quIOYaTr6CUy: "Speaking"
    }
 },
 1: {...},
 2: {...}
]

I would like to change the coreCompetencies into an array of values e.g. ["Grammar", "Listening", "Reading", "Writing", "Speaking"] while preserving the other data. I've tried .map but got confused as it only returns the coreCompetencies object, without the other details. This is what I did that returned only the coreCompetencies object:

const datacore = datasubject.map(value => value.coreCompetencies);

I would like to achieve something like this:

const datasubject = 
[
 0: {
    level: "standard 3"
    subject: "English"
    _id: xxx
    coreCompetencies ["Grammar","Listening","Reading","Writing","Speaking"]
 },
 1: {...},
 2: {...}
]

解决方法

const datacore = datasubject.map(({coreCompetencies, ...rest})=> {
  return {...rest, coreCompetencies: Object.values(coreCompetencies)}
})
相似信息