Reputation: 2466
I need to add true
after splitting string into array:
var str = "California,Nevada";
var array = value.split(',');
this.setState({ value: array });
console.log(this.state.value)
// result is ["California", "Nevada"]
I needed result like this:
{California: true, Nevada: true}
Upvotes: 0
Views: 227
Reputation: 50291
You can use array#map function along with split
to create the new object
var newObj = {};
var str = "California,Nevada".split(',').map(function(item) {
newObj[item] = true;
});
console.log(newObj)
Upvotes: 2
Reputation: 4956
Assuming you want to split str
and not value
in the second line, you can do something like below.
var str = "California,Nevada";
var array = str.split(',');
// I think you need to use this.state instead of state
var state = {};
array.forEach(item => state[item]=true);
console.log(state)
Upvotes: 0
Reputation: 7575
So what you wanna do is creating a new object and then iterate over the splitted input like this:
const input = "California,Nevada";
const output = {};
input.split(',').forEach( item => output[ item ] = true );
console.log( output );
Upvotes: 0
Reputation: 7488
You could try this:
var str = "California,Nevada";
var result = {};
str.split(',').forEach(function(e){
result[e] = true;
});
console.log(result);
Upvotes: 1