从对象数组创建单个对象-JS / ES6

时间:2019-02-24 02:26:32

标签: javascript arrays reactjs object ecmascript-6

我有一个数组:

[
    {"allocateProd1": "30.0000"}, 
    {"allocateProd2": "0"}, 
    {"allocateProd3": "0"},
    {"allocateProd4": "30"}
]

此数组是动态生成的,因为其中的对象数取决于数据

我需要一个对象:

{
    "allocateProd1": "30.0000", 
    "allocateProd2": "0", 
    "allocateProd3": "0", 
    "allocateProd4": "30"
}

大多数将在React中使用它。 JS / ES6解决方案会有所帮助

2 个答案:

答案 0 :(得分:3)

一种替代方法是使用函数reduce + spread syntax

let arr = [
    {"allocateProd1": "30.0000"}, 
    {"allocateProd2": "0"}, 
    {"allocateProd3": "0"},
    {"allocateProd4": "30"}
];

let result = arr.reduce((a, c) => ({...a, ...c}), Object.create(null));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

替代方法是使用函数Object.assign

let arr = [
    {"allocateProd1": "30.0000"}, 
    {"allocateProd2": "0"}, 
    {"allocateProd3": "0"},
    {"allocateProd4": "30"}
];

let result = arr.reduce((a, c) => Object.assign(a, c), Object.create(null));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

出于完整性考虑,只需将一个对象作为目标,将数组和spread ...个对象放入Object.assign中。瞧!

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';

import Navbar from '../components/layout/Navbar';
import Sidebar from '../components/layout/Sidebar';
import Breadcrumbs from '../components/layout/Breadcrumbs';
import TextFieldGroup from '../components/form-components/TextFieldGroup';

import { getPatientById } from '../redux/actions/patient.actions';

class PatientEdit extends Component {
  constructor() {
    super();
    this.state = {
      firstName: '',
      lastName: '',
      errors: {}
    };
  }

  componentDidMount = () => {
    if (this.props.match.params.patient_id) {
      this.props.getPatientById(this.props.match.params.patient_id);
    }
  };

  componentWillReceiveProps = nextProps => {
    if (nextProps.errors) {
      this.setState({ errors: nextProps.errors });
    }

    if (nextProps.patients.patient) {
      const patient = nextProps.patients.patient;
      this.setState({
        firstName: patient.firstName.patients,
        lastName: patient.lastName.patients
      });
    }
  };

  onChange = e => {
    this.setState({ [e.target.name]: e.target.value });
  };

  onSubmit = (e, patient_id) => {
    e.preventDefault();
    // boring script to handle form submission...
  };

  render() {
    const { errors } = this.state;
    const { patient } = this.props.patients;

    return (
      <>
        <Navbar />
        <div className="app-body">
          <Sidebar />
          <main className="main">
            <div className="container">
              <form onSubmit={e => this.onSubmit(e, patient._id)}>
                <div>
                  <input
                    type="text"
                    name="firstName"
                    value={this.state.firstName}
                    onChange={this.onChange}
                  />
                  <input
                    type="text"
                    name="lastName"
                    value={this.state.lastName}
                    onChange={this.onChange}
                  />
                </div>
                <div>
                  <Link to="/patients" className="btn btn-light mr-2">
                    Cancel
                  </Link>
                  <button type="submit" className="btn btn-primary">
                    Submit
                  </button>
                </div>
              </form>
            </div>
          </main>
        </div>
      </>
    );
  }
}

PatientEdit.propTypes = {
  getPatientById: PropTypes.func.isRequired,
  patients: PropTypes.object.isRequired,
  errors: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
  patients: state.patients,
  errors: state.errors
});

export default connect(
  mapStateToProps,
  { getPatientById }
)(PatientEdit);