Raheel
Raheel

Reputation: 9024

Javascript array reduce convert array to object with integer keys

I am trying to convert an array of objects to objects with reduce method. The problem is I want to have object keys in numeric.

let crops = [{
  id: 1,
  name: "wheat"
}, {
  id: 2,
  name: "rice"
}];

let cropsObj = crops.reduce((accumulator, currentValue) => {
  accumulator[currentValue.id] = currentValue.name
  return accumulator;
}, {});

console.log(cropsObj);

This works fine except the keys I am getting are strings. For example:

{"1":"wheat","2":"rice"}

What I want is {1:"wheat",2:"rice"}. How can I convert the keys to integers?

Upvotes: 1

Views: 584

Answers (3)

junvar
junvar

Reputation: 11574

To illustrate @MarkMeyer's comment:

Keys can only be strings (or Symbols) in javascript objects.

console.log({3: 4, '3': 5});

Upvotes: 2

Ajit Kumar
Ajit Kumar

Reputation: 1505

let obj = {
  key: 4,
  123: 'one two three',
  1: 'one'
};

console.log(obj.key);
//console.log(obj.1); error
console.log(obj["1"]);
console.log(obj["123"]);

console.log(obj[1]);
console.log(obj[123]);

It is not possible because key in any JavaScript object is a JavaScript identifier or a string.

Upvotes: 1

Leftium
Leftium

Reputation: 17903

For your purposes (using material-table), your current objects will work fine. {1:"wheat"} is effectively the same as {"1":"wheat"}.

Unquoted property names / object keys in JavaScript gives a very detailed explanation of why. In short, numeric property names can be used, but they will be coerced into strings.

Upvotes: 1

Related Questions