Home > Mobile >  How to convert array element into object with conditionally true and one string value in javaScript
How to convert array element into object with conditionally true and one string value in javaScript

Time:09-30

What is a more compact way to convert color=["red", "green", "blue", "Other"] into colorObjFinal = { blue: true, green: true, Other: "Other", red: true }?

This is my long function, I would like to shorten it:

let color = ["red", "green", "blue", "Other"];
let colorObj;
let colorObjFinal = {};
console.log("color:", color);

colorObj = color.reduce((a, v) => ({
...a,
[v]: v
}), {});
console.log("colorObj:", colorObj)

for (var key in colorObj) {
    if (colorObj.hasOwnProperty(key)) {
        if(key == 'Other'){
        colorObjFinal[key] = colorObj[key];
      } else {
        colorObjFinal[key] = true;
      }
    }
}

console.log("colorObjFinal:", colorObjFinal)

CodePudding user response:

You could just do it all in 1 go:

let color = ["red", "green", "blue", "Other"];

let result = color.reduce ((a,v) => ({
  ...a,
  [v] : v == "Other" ? v : true
}),{});

console.log(result);

CodePudding user response:

You can change your first Array.reduce to get the result.

let color = ["red", "green", "blue", "Other"];

const result = color.reduce((acc, item) => {
   acc[item] = (item != "Other") ? true : item;
   return acc;
}, {});

console.log(result);

CodePudding user response:

that ? (is arguably the most compact writing here)

let color = ["red", "green", "blue", "Other"];

const res = color.reduce((a,c)=>(a[c]=c=='Other'?c:true,a),{});

console.log(res);

CodePudding user response:

You can make use of Array.reduce function here:

const color=["red", "green", "blue", "Other"];
const transformedObj = color.reduce((a,b)=> ({...a, [b]: b !=="Other"? true: "Other"}),{});
console.log(transformedObj )

CodePudding user response:

Sth like this:

["red", "green", "blue", "Other"].map(e => ({[e]: e == 'Other' ? e : true}))

enter image description here

  • Related