How to fill an object with array properties?

0

Hello, I have a component in React that has a state type object: items: {} and my goal is to fill it with properties type fix. Example if input into a input a value is created: items: {Cat []} and if then input another value is created items: {Cat [], Dog [], ... etc}. In the variable s, the value of the input is arriving and the Lists array is filling correctly, the problem is with the items object. Please someone to help me

import React, { Component } from 'react';
import Lists from './Lists.js';
import AddList from './AddList.js';
import './App.css';

class App extends Component {

 constructor() {
super();
this.state = {
lists: [], // this holds the name of each list
items: {} // this property names of this object are the names of the lists; 
their values are arrays of the items in each list
};
}


handleAddList(s) {
  // Implement this function!
  let nameList = s;

  this.setState({ lists: this.state.lists.concat(nameList)  });
  this.setState({ items: this.state.items.[nameList] = []  });
  console.log(this.state.items);

}


handleAddItem(s) {
  // Implement this function!
  let itemName = s;

}    
/**
 * Renders the component.
 */
 render() {
 return (
  <div className="App">
    <AddList addList={this.handleAddList.bind(this)} />
    <div id="listsDiv" className="List">
      <Lists lists={this.state.lists} items={this.state.items} addItem=
  {this.handleAddItem.bind(this)} />
    </div>
  </div>
 );
}

}

export default App;
    
asked by user3821102 13.03.2018 в 19:04
source

1 answer

1

There are several ways to do that.

1 - Simple:

First create a copy of items and then make the changes on that copy:

// creando copia de objeto
let items = Object.assign({}, this.state.items);
items[nameList] = [];
this.setState({ items });

Instead of using Object.assign we can also write it like this:

let items = {...this.state.items};

2 - Using spread operator :

this.setState(prevState => ({
  items: {
    ...prevState.items,
    [nameList]: []
  }
}))
    
answered by 13.03.2018 / 20:30
source