I have an array:
[ 'Item 1', 'Item 2', 'Item 3' ]
I need the final result to be
{ 'Item 1':true, 'Item 2':true, 'Item 3':true }
Using ES6 I got kinda close with this:
let arr = [];
for (let m of crmData.modRequired) {
let i = m + ':true';
arr.push(i);
}
modReq = JSON.stringify(arr);
modReq = modReq.replace(/\[/, '{');
modReq = modReq.replace(/\]/, '}');
But that produced:
{"Quotes:true","Flight Logs:true","Currency Records:true","FTD:true","Maintenance Tracker:true"}
You can do this very easily with Object.assign
and Array.map
, like so:
The idea is to map your array of values into an array of objects that follow the {"ItemX": true}
pattern, and then combine them into a single object using Object.assign
.
var items = ["Item 1", "Item 2", "Item 3"];
var mapped = Object.assign({}, ...items.map(item => ({[item]: true})));
console.log(JSON.stringify(mapped));
You should be able to do this using the array .reduce
method. That will turn the array into the object you want. Then you can use JSON.stringify
to transform that into a json string.
const myArray = [ 'Item 1', 'Item 2', 'Item 3' ]
// I need the final result to be
// { 'Item 1':true, 'Item 2':true, 'Item 3':true }
const myObj = myArray.reduce((obj, key) => {
obj[key] = true;
return obj;
}, {});
console.log("javascript object:", myObj);
console.log("json string:", JSON.stringify(myObj))
Just build the object as you loop the array (one step) and you won't have to replace any braces or brackets.
var ary = [ 'Item 1', 'Item 2', 'Item 3' ];
var obj = {};
ary.forEach(function(itm) { obj[itm] = true; } );
console.log(obj);
objJSON = JSON.stringify(obj);
console.log(objJSON);
Use the function reduce
with Spread Syntax
var array = [ 'Item 1', 'Item 2', 'Item 3' ],
result = array.reduce((a, c) => ({...a, ...{[c]: true}}), {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Using forEach
var array = [ 'Item 1', 'Item 2', 'Item 3' ],
result = {};
array.forEach(c => result[c] = true);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
use .forEach
let arr = [ 'Item 1', 'Item 2', 'Item 3' ];
let newArr = {};
arr.forEach(item=>{
newArr[item] = true;
});
console.log(newArr);
however i prefer mhodges answer:
let arr = [ 'Item 1', 'Item 2', 'Item 3' ];
console.log(Object.assign({}, ...arr.map(item => ({[item]: true}))))