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

3 Answers 3

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

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

Comments

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);

Comments

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);

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.