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

时间:2019-03-07 02:35:45

标签: javascript arrays object

我有以下对象数组:

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: {...}
]

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

您应该执行以下操作:

const Input = ({ id }) => <div>{id}</div>

class Foo extends React.Component {
  state = {
    arr: [
      <Input id={1} />,
      <Input id={2} />,
      <Input id={3} />,
      <Input id={4} />,
    ],
    id: 5,
  }

  addToArray = () => {
    const arr = [...this.state.arr, <Input id={this.state.id} />]
    this.setState(prevState => ({ arr, id: prevState.id + 1 }))
  }

  removeFromArray = () => {
    const id = parseInt(window.prompt("Enter index"))

    this.setState(prevState => ({
      arr: prevState.arr.filter(element => element.props.id !== id),
    }))
  }

  render() {
    return (
      <div>
        <div>
          <button onClick={this.addToArray}>Add to array</button>
        </div>
        <div>
          <button onClick={this.removeFromArray}>Remove from array</button>
        </div>
        Array: {this.state.arr}
      </div>
    )
  }
}

ReactDOM.render(<Foo />, document.getElementById("root"))