1

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)

0

4 Answers 4

2

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);

Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

1

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);

Comments

0

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 )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.