dan_boy
dan_boy

Reputation: 2019

How to merge nested arrays into a new object?

I am struggeling a bit to merge nested arrays into a new object.

I have an array with nested objects in it. The objects contain an array. Now I want to merge the entries of this array into a new object and assign a value to it. For example "false". Please see the example.

Current Structure:

const arr = [
        {
            baa: "some",
            foo: ["1", "2", "3"],
        },
        {
            baa: "some",
            foo: [
                "4",
                "5",
                "6",
                "7",
            ],
        },
    ]

Target Structure: merge "foo" entries into object and assign value.

const obj = {
    1: false,
    2: false,
    3: false,
    4: false,
    5: false,
    6: false,
    7: false,
};

Upvotes: 0

Views: 414

Answers (4)

Pandaiolo
Pandaiolo

Reputation: 11586

More declarative answer:

const arr = [
  {
    baa: "some",
    foo: ["1", "2", "3"],
  },
  {
    baa: "some",
    foo: ["4", "5", "6", "7"],
  },
];

// Build `obj` from `arr`

const obj = Object.fromEntries(
  arr.map(val => val.foo)
     .flat()
     .map(
       key => [key, false]
     )
)

console.log(obj)

Side note: not compatible with legacy browsers such as IE11, see coverage here: https://caniuse.com/mdn-javascript_builtins_object_fromentries

Upvotes: 2

user13548229
user13548229

Reputation:

While the other answers are correct I find them so much harder to read than a simple double loop.

let result = {}
for(let obj of arr){
  for(let innerArrElem of obj.foo){
    result[innerArrElem] = false
  }}
}}

Upvotes: 1

munleashed
munleashed

Reputation: 1685

function populate(arr, value) {

  return arr.reduce((acc, element) => {

         element.foo.forEach((f) => acc[f] = false);
         return acc;

         }, {})

  }

Upvotes: 0

DecPK
DecPK

Reputation: 25416

Fetch the array foo and iterate over using forEach and get the value and make it a property, You can do this using reduce.

const arr = [
  {
    baa: "some",
    foo: ["1", "2", "3"],
  },
  {
    baa: "some",
    foo: ["4", "5", "6", "7"],
  },
];
const result = arr.reduce((acc, curr) => {
  const { foo } = curr;
  foo.forEach((el) => (acc[el] = false));
  return acc;
}, {});

console.log(result);

Upvotes: 3

Related Questions