Home > Mobile >  Stuck transforming an Object structure
Stuck transforming an Object structure

Time:03-20

Given an object in the form:

{
  attributeA: ['valA1', 'valA2'],
  attributeB: ['valB1'],
  attributeC: ['valC1', 'valC2', 'valC3'],
}

I would like to transform it to:

{
  attributeA: false,
  valA1: false,
  valA2: false,
  attributeB: false,
  valB1: false,
  attributeC: false,
  valC1: false,
  valC2: false,
  valC3: false,
}

I'm not versatile using the reduce method but I got as far as this:

Object.entries(attributes).reduce((p, c) => {
   return [].concat(p, c[0], c[1]);
}, []);

Which returns an array of all elements and its values like:

[attributeA, valA1, valA2, attributeB, valB1, attributeC, valC1, valC2, valC3]

I'm having a hard time to properly define my reduce function to return the output I need

CodePudding user response:

I'd keep it simple and use loops:

const result = {};
for (const [name, array] of Object.entries(original)) {
    result[name] = false; // attributeA, etc.
    for (const value of array) {
        result[value] = false;
    }
}

const original = {
    attributeA: ["valA1", "valA2"],
    attributeB: ["valB1"],
    attributeC: ["valC1", "valC2", "valC3"],
};

const result = {};
for (const [name, array] of Object.entries(original)) {
    result[name] = false; // attributeA, etc.
    for (const value of array) {
        result[value] = false;
    }
}

console.log(result);

...but it is possible to do it with a combination of Object.fromEntries, Object.entries, and flatMap:

const result = Object.fromEntries(
    Object.entries(original).flatMap(([key, array]) => [[key, false], ...array.map(value => [value, false])])
);

const original = {
    attributeA: ["valA1", "valA2"],
    attributeB: ["valB1"],
    attributeC: ["valC1", "valC2", "valC3"],
};

const result = Object.fromEntries(
    Object.entries(original).flatMap(([key, array]) => [[key, false], ...array.map(value => [value, false])])
);

console.log(result);

CodePudding user response:

// Object
const obj = {
  attributeA: ['valA1', 'valA2'],
  attributeB: ['valB1'],
  attributeC: ['valC1', 'valC2', 'valC3'],
};

// Define new object
let newObj = {};

// Simple loop of object
for(const el in obj) {
  // Put element name in new object
  newObj[el] = false;
  // Loop through el value and add them to
  // new object
  for(const item of obj[el]) newObj[item] = false;
}

// Test
console.log(newObj);

CodePudding user response:

You can use Array.prototype.reduce() to make the object,
Inside each iteration, create the key and iterate the value which is an array with Array.prototype.forEach():

const obj = {
  attributeA: ['valA1', 'valA2'],
  attributeB: ['valB1'],
  attributeC: ['valC1', 'valC2', 'valC3'],
}

const res = Object.entries(obj).reduce((acc, [key, value]) => {
  acc[key] = false;
  value.forEach(item => acc[item] = false);

  return acc;
}, {});

console.log(res);

  • Related