Reduce javascript object

791 views Asked by At

I have this javascript object :

{
    {
        long_name: "10",
        types: [
            0: "street_number"
        ],
    },
    {
        long_name: "street",
        types: [
            0: "route"
        ],
    },
    {
        long_name: "Paris",
        types: [
            0: "locality"
        ],
    },
    ...
}

And I want to flatten it and have something like :

{
    street_number: "10",
    route: "street",
    locality: "Paris",
    ...
}

I am using ES6, but can't manage to flatten it this much, All I've succeeded to do is having :

{
    {street_number: "10"},
    {route: "street"},
    {locality: "Paris"},
    ...
}

Here is what I Tried :

const flattenedObject = originalObject.map(flatten);
...
function flatten(element) {
    let obj = {};
    obj[element.types[0]] = element.long_name;

    return obj;
}

Thanks for any help.

2

There are 2 answers

2
Nina Scholz On BEST ANSWER

You could use Array#reduce with a computed property and the first element only from the array.

The key feature is Object.assign for adding properties to the result object.

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

var data = [{ long_name: "10", types: ["street_number"], }, { long_name: "street", types: ["route"], }, { long_name: "Paris", types: ["locality"], }],
    object = data.reduce((r, a) => Object.assign(r, { [a.types[0]]: a.long_name }), {});

console.log(object);

0
AudioBubble On

All I've succeeded to do is having:

{
  {street_number: "10"},
  {route: "street"},
  {locality: "Paris"},
  ...
}

I don't how you "succeeded" in getting that, since no such kind of object exists in JS (nor does your original object). Did you mean to put [] around it instead of {} (in other words, is it an array of little objects)? If so, then combine with

 Object.assign({}, ...littleObjects)

By the way, you can call this "flattening" if you want, but it will be confusing, since it's quite different from what people usually refer to as "flattening" (meaning to collapse nested arrays).