David Karlsson
David Karlsson

Reputation: 9696

Reducing array of objects to hashmap in JS

Hi I am trying to transform a JSON data type from one format to another:

  [ { name: 'CarNo', attributes: {}, children: [], content: '?' },
       { name: 'AccNo', attributes: {}, children: [], content: '?' },
     { name: 'SCS', attributes: {}, children: [], content: '?' }]

The target object would be based on the name property and the content property:

   {'CarNo': '?', 'AccNo': '?', 'SCS': '?' }

I was thinking I could just reduce this but I am failing:

        const filteredResponseObj = Object.keys(rawResponseBodyObj).reduce((p,c)=>{
          if( c === 'name' ){
            p[c]=rawResponseBodyObj[c].content;
          }
          return p;
        },{});

What am I missing? clearly I have some issues with the reduction...

Upvotes: 3

Views: 7558

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386600

You could use Object.assign with spread syntax ... and Array#map for the object generation.

var array = [{ name: 'CarNo', attributes: {}, children: [], content: '?' }, { name: 'AccNo', attributes: {}, children: [], content: '?' }, { name: 'SCS', attributes: {}, children: [], content: '?' }],
    result = Object.assign(...array.map(o => ({ [o.name]: o.content })));

console.log(result);

Upvotes: 2

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

With this line c === 'name' you are trying to compare an object from the initial array with string name. Such comparison will always give false

The right way should be as below:

var arr = [ { name: 'CarNo', attributes: {}, children: [], content: '?' },
    { name: 'AccNo', attributes: {}, children: [], content: '?' },
    { name: 'SCS', attributes: {}, children: [], content: '?' }],

    filtered = arr.reduce(function (r, o) {
        if (!r[o.name]) r[o.name] = o['content'];
        return r;
    }, {});

console.log(filtered);

Upvotes: 0

Xavier Delamotte
Xavier Delamotte

Reputation: 3599

You had the right idea, but here is how to do it:

const filteredResponseObj = rawResponseBodyObj.reduce(function(map, obj) {
    map[obj.name] = obj.content;
    return map;
}, {});

Using Convert object array to hash map, indexed by an attribute value of the Object

Upvotes: 5

Related Questions