• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

269
Views
How to convert array element into object with conditionally true and one string value in javaScript

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)

almost 3 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

almost 3 years ago · Juan Pablo Isaza Report

0

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

almost 3 years ago · Juan Pablo Isaza Report

0

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

almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error