3

I have a data that is like following:

const data = [{
    ratings: [ { rating: 5 } ],
    counts: [ { count: 100 } ],
}];

And I want to flatten it in a sense that I want to get rid of arrays and have only objects, and end result to be:

const data = {
   ratings: { rating: 5 },
   counts: { count: 100 },
};

I tried to do something like this, but it is wrong and I believe I'm kind of over complicating it.

const flatten = data => {
                return data.reduce((r, { ...children }) => {
                    Object.assign(children, r);
                    if (children) Object.assign(flatten(...Object.values(children)), r);
                    return r;
                }, {})
              }

Any ideas?

2
  • Is there only one object every array? Commented Dec 1, 2018 at 13:28
  • @Eddie No, some have more. But, basically all arrays are composed of single element, which is itself an object. Commented Dec 1, 2018 at 13:29

3 Answers 3

8

You could create recursive function with reduce method to turn all arrays to objects assuming you have just objects in those arrays.

const data = [{ratings: [ { rating: 5 } ],counts: [ { count: 100 } ]}];

function flatten(arr) {
  return arr.reduce((r, e) => {
    const obj = Object.assign({}, e);
    for (let p in obj) {
      if (Array.isArray(obj[p])) {
        obj[p] = flatten(obj[p])
      }
    }
    return Object.assign(r, obj)
  }, {})
}

console.log(flatten(data))

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

Comments

2

If by any chance the data is result from JSON.parse :

var json = JSON.stringify( [{ratings:[{rating: 5}], counts:[{count: 100}]}] )

var result = JSON.parse(json, (k, v) => v[0] || v)

console.log( result )

Comments

1

Please check:

var data = [{ratings: [ { rating: 5 } ], counts: [ { count: 100 } ]}];

var flatten = function(data) {
  if (Array.isArray(data)) {
    data = data[0];
    for (var key in data) data[key] = flatten(data[key]);
  }
  return data;
}

console.log(flatten(data));

Please check @ CodePen https://codepen.io/animatedcreativity/pen/842e17d2b9f83bc415513f937fc29be8

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.