Search code examples
javascriptarraysdestructuring

Destruct using titles


I have answered a few questions using destructing, I just want to take this one to the next level

I want to not use reduce in this example but pure destructing if at all possible

So the data's first row contains the attribute names of the object, How can I use that to be DRY

i.e. I hoped for

const obj = data.slice(1).map((titles) => ({ titles }) )

or similar

So this works, but I miss one more step:

const data = [
    ["fruits","frozen","fresh","rotten"],
    ["apples",884,494,494],
    ["oranges",4848,494,4949],
    ["kiwi",848,33,33]
]
const titles = data[0]; // not used below but I want to use it
const obj = data.slice(1).map(([fruits,frozen,fresh,rotten]) => ({ fruits,frozen,fresh,rotten }) )
console.log(obj)


Solution

  • You could map the entries for an object.

    const
        data = [["fruits", "frozen", "fresh", "rotten"], ["apples", 884, 494, 494], ["oranges", 4848, 494, 4949], ["kiwi", 848, 33, 33]],
        mapWith = keys => values => Object.fromEntries(keys.map((k, i) => [k, values[i]])),
        getArray = ([keys, ...data]) => data.map(mapWith(keys)),
        array = getArray(data);
    
    console.log(array);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    Old simpler example

    const data = [
      ["fruits", "frozen", "fresh", "rotten"],
      ["apples", 884, 494, 494],
      ["oranges", 4848, 494, 4949],
      ["kiwi", 848, 33, 33]
    ]
    const titles = data[0];
    
    const obj = data.slice(1).map(
      arr => Object.fromEntries(
        titles.map( 
          (t, i) => [t, arr[i]] 
        )
      )
    );
    
    console.log(obj);
    .as-console-wrapper { max-height: 100% !important; top: 0; }