Natanael Medina
Natanael Medina

Reputation: 87

Combine array of keys and array of values into object

I have an array with labels

columns = ["col1", "col2", "col3", "col4"]

and thousands of arrays with values

values = [ 
    ['value1','value2','value3','value4'],
    ['value1','value2','value3','value4'],
    ['value1','value2','value3','value4'],
    // ...
]

I want to iterate the values and create a single array with this structure:

result = [ 
    { col1: "val1", col2: "val2", col3: "val3", col3: "val4" },
    { col1: "val1", col2: "val2", col3: "val3", col3: "val4" },
    { col1: "val1", col2: "val2", col3: "val3", col3: "val4" },
]

I tried to iterate both and return the object dynamically, but without success:

const columns = ["col1", "col2", "col3", "col4"];
const values = [ 
    ['value1','value2','value3','value4'],
    ['value1','value2','value3','value4'],
    ['value1','value2','value3','value4'],
];

const lastArr = values.map((e) =>
    columns.map((col) => {
        return { col: e[0] };
    })
);

console.log(lastArr);

// or manually 

const raw = values.map(e => 
    columns.map(col => {
        return {
            col1: e[0],
            col2: e[1],
            col3: e[2],
            col4: e[3],
        }
    })
);

console.log(raw);

Neither attempts return the desired result.

Upvotes: 1

Views: 98

Answers (3)

derpirscher
derpirscher

Reputation: 17382

It would be more understandable if your examples were more consistent and the values were a bit more distinguishable but this should do the trick

values.map(v => Object.fromEntries(columns.map((c,i) => [c, v[i]])));

Upvotes: 1

Yong Shun
Yong Shun

Reputation: 51220

Traditional JS way to use .reduce() to transform array to new array (form).

Inner part loop to iterate the column array and current iterated item of values, and next add as key-value pair into an object.

let columns = ["col1",
    "col2",
    "col3",
    "col4"
]

let values = [
    ['value1', 'value2'],
    ['value1', 'value2'],
    ['value1', 'value2']
]

let result = values.reduce((acc, cur) => {
    let obj = {};

    for (let i = 0; i < columns.length; i++)
    {
        obj[columns[i]] = cur[i];
    }

    acc.push(obj);

    return acc;
}, []);

console.log(result);

Upvotes: 0

trincot
trincot

Reputation: 350272

You can use Object.fromEntries, like so:

const columns = ["col1", "col2", "col3"];
const values = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
    [10, 11, 12]
];

const result = values.map(row =>
    Object.fromEntries(columns.map((col, i) =>
        [col, row[i]]
    ))
)

console.log(result);

Upvotes: 3

Related Questions