1

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?

7
  • 7
    Keys can only be strings (or Symbols) in javascript objects. If you need some other key an es6 Map might be an option. Commented May 24, 2019 at 20:53
  • An array has integer "keys", but there are performance implications to sparse arrays. You might want to look into Map... Commented May 24, 2019 at 20:54
  • @HereticMonkey If neglecting performance for a moment, How will I have integer keys ? Commented May 24, 2019 at 20:57
  • 1
    {"1":"wheat","2":"rice"} and {1:"wheat",2:"rice"} are same thing, JS internally converts them to string Commented May 24, 2019 at 20:57
  • 1
    @RaheelKhan that is still the same thing Commented May 24, 2019 at 21:00

3 Answers 3

2

To illustrate @MarkMeyer's comment:

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

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

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

Comments

1

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.

Comments

1

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.

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.