0

I have object like picture below.

enter image description here

I want to use map() to retrieve the object like

{
  "2643216":{pg:1,pt:1},
  "1304681":{pg:1,pt:1}
}

Here is my code.

Object.keys(obj).map(function(x){
                return {obj[x].number:{'pg':obj[x].pg,'pt':obj[x].pt}}
                })

But errors may appear at the obj[x].number.

The debug errors notifies me the ignorance of the : (colon).

Is there mistake I make and any adjustment you can suggest-

or other way can retrieve the object I want?

Thank you.

Hsinhsin Hung
  • 343
  • 1
  • 2
  • 12

2 Answers2

1

this should do the job:

function groupByNumber(data) {

  return Object
    .keys(data)
    .reduce(function(result, key) {
      var value = data[key];

      result[value.number] = { pt: value.pt, pg: value.pg };

      return result;
    }, {});
};

var data = {
  'LKB_something': { number: 1, pg: 1, pt: 5 },
  'LKB_something_else': { number: 2, pg: 1, pt: 5 },
  'LKB_something_else_1': { number: 3, pg: 1, pt: 5 },
};

console.log('result', groupByNumber(data));

// ES-NEXT would let you be more coincise
const groupByNumber = data => Object.values(data).reduce(
  (result, { number, ...rest }) => ({ ...result, [number]: rest }),
  {},
);
Hitmands
  • 13,491
  • 4
  • 34
  • 69
0

For a dynamic key in a JavaScript object, you need square brackets to make a computed property name:

return { [obj[x].number]: { "pg": obj[x].pg, "pt": obj[x].pt }}

And your code could be simplified using Object.values and the implicit return of an arrow function, along with destructuring and shorthand property notation, like so:

Object.values(obj).map(({ number, pg, pt }) => ({ [number]: { pg, pt }}))

Note that the above returns an array of objects - if you want an object:

Object.values(obj).reduce((a, { number, pg, pt }) => ({ ...a, [number]: { pg, pt }}), {})
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79