0

How to set value for all the items inside an array?

For example, I have the array: ["chin","eng","maths"]

I want to set it to {"chin" :true,"eng":true,"maths":true}

And push to firebase as a child.

enter image description here

1
  • You mean changing ["chin","eng","maths"] to {"chin" :true,"eng":true,"maths":true} as a structure? Or as a string? The simple fact of changing [] to {} means a different structure. ([] = Array, {} = Object) Commented May 29, 2019 at 19:02

2 Answers 2

4

One possible approach is to use Array.reduce() like this:

const input = ["chin", "eng", "maths"];

let obj = input.reduce((acc, item) => (acc[item] = true, acc), {});

console.log(obj);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Or, you can go with spreading, but with a little overhead on performance:

let obj = input.reduce((acc, item) => ({...acc, [item]: true}), {});
Sign up to request clarification or add additional context in comments.

4 Comments

Does that create a new object each iteration? Seems expensive.
Probably just as expensive as doing what youd already be doing without using reduce
"In case performance" - yes when a solution is shorter, performs better and is just as readable, I guess that should be the primary answer.
@James yeah, you right, I have added a better version without spreading.
1

The simplest way is to loop through the array using for...of and add each key to an object:

const keys = ["chin", "eng", "maths"],
      output = {};

for (const key of keys) {
  output[key] = true;
}

console.log(output)

Another option is to create a 2D array of key-value pair entries using map. Then use Object.fromEntries() to create the object

const keys = ["chin","eng","maths"]
const output = Object.fromEntries(keys.map(k => [k, true]))

console.log(output)

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.