3

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...

David Karlsson
  • 9,396
  • 9
  • 58
  • 103

3 Answers3

5

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

Community
  • 1
  • 1
Xavier Delamotte
  • 3,519
  • 19
  • 30
2

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

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);
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105