1

I have an array of string names and i want to do bellow

  let accountcode:{a:1,b:2};
    let array=["first","second",third];
    this.setState({[array[0]:accountCode,array[1]:accountCode,array[3]:accountCode]})

but array is dynamic list and i should map in array and setState every item of it in one setState i try

 object.setState(
        {...stateName:accountCodes}
      )

but not working and i also try below and not throw syntax error:

 object.setState(
        stateName.map(s=>{[s]=accountCodes})
      )

what should i do?

Aref Zamani
  • 2,023
  • 2
  • 20
  • 40

3 Answers3

2

You could use the reduce function to achieve it. Each iteration in your array will add the element to your object with a computed property :

const accountcode = { a: 1, b: 2 };
const array = ["first","second","third"];
this.setState(array.reduce((acc, val) => ({[val]: accountcode, ...acc}), {}));

Working example :

class App extends React.Component {
    componentDidMount(){
        const accountcode = { a: 1, b: 2 };
        const array = ["first", "second", "third"];
        this.setState(array.reduce((acc, val) => ({ [val]: accountcode, ...acc }), {}));
    }

    render(){
        console.log(this.state)
        return <div></div>
    }
}

ReactDOM.render(<App/>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.1/umd/react-dom.production.min.js"></script>
<div id='root'>
Treycos
  • 7,373
  • 3
  • 24
  • 47
1

You're looking at creating an object from an array. The question is just a rephrase of creating an object from an array.

In your case, the solution may be as follows:

let accountCode = {a: 1, b: 2};
let array = [1, 2, 3, 4];

let output = {};
for (let key of array) {
    output[key] = accountCode;
}

// Almost forgot this
this.setState(output);
cross19xx
  • 3,170
  • 1
  • 25
  • 40
0

You can simply write something like this:

let accountCode = {a:1, b:2};
let array = ["first", "second", "third"];

/* Function in which you will call setState */
let newState = {};
array.forEach(el => {
  newState[el] = accountCode;
});

Though, I suggest you to not simply write newState[el] = accountCode; otherwise you are using the same Object for each property of newState. You could write newState[el] = JSON.parse(JSON.stringify(accountCode)); to prevent that!

Jolly
  • 1,678
  • 2
  • 18
  • 37