I have two arrays as follows,
columnNames = ['KEY_ID', 'SOURCE_ID', 'MTNAME', 'MTNO', 'PLANTS']
columnValues = [{col0:"719801", col1: "4198", col2: "010", col3: "200887", col4: "6LLA"}, {col0:"719901", col1: "5198", col2: "011", col3: "207887", col4: "6PPA"}]
My expected output is,
outputArray = [KEY_ID:"719801", SOURCE_ID: "4198", MTNAME: "010", MTNO: "200887", PLANTS: "6LLA"]
The number of items and contents of both arrays change dynamically i.e., columnNames can have different names and columnValues can have any number of values. Any inputs to obtain the final outputArray will be highly helpful. I have tried using reduce. It either requires multiple iterations or the columnNames array to be constant.
let renameKeys = (columnValues, object) =>
Object.keys(object).reduce(
(acc, key) => ({
...acc,
...{ [columnValues[key] || key]: object[key] },
}),
{}
);
console.log(renameKeys(columnNames,columnValues))
CodePudding user response:
Your columnValues is not an object as it has square brackets
This will ONLY work if there are as many names as values:
const columnNames = ['KEY_ID', 'SOURCE_ID', 'MTNAME', 'MTNO', 'PLANTS'],
columnValues = {col0:"719801", col1: "4198", col2: "010", col3: "200887", col4: "6LLA"}
let renameKeys = (columnValues, object) =>
Object.values(object).reduce((acc, val, i) => {
acc[columnNames[i]] = val;
return acc},
{});
console.log(renameKeys(columnNames, columnValues))
CodePudding user response:
This will work for you !
let columnNames = ['KEY_ID', 'SOURCE_ID', 'MTNAME', 'MTNO', 'PLANTS']
let columnValues = [{col0:"719801", col1: "4198", col2: "010", col3: "200887", col4: "6LLA"}, {col0:"719901", col1: "5198", col2: "011", col3: "207887", col4: "6PPA"}]
renameKey = (obj, old_key, new_key) => {
// check if old key = new key
if (old_key !== new_key) {
Object.defineProperty(obj, new_key, // modify old key
// fetch description from object
Object.getOwnPropertyDescriptor(obj, old_key));
delete obj[old_key]; // delete old key
}
}
columnValues.map((cv)=>{
Object.keys(cv).map((keys,index)=>{
renameKey(cv,keys,columnNames[index])
})
})
console.log(columnValues)
CodePudding user response:
Your expected output array is not valid. It should be an array of objects. You can achieve this requirement by iterating the input array with the help of Array.forEach()
.
Live Demo :
const columnNames = ['KEY_ID', 'SOURCE_ID', 'MTNAME', 'MTNO', 'PLANTS'];
const columnValues = [{col0:"719801", col1: "4198", col2: "010", col3: "200887", col4: "6LLA"}, {col0:"719901", col1: "5198", col2: "011", col3: "207887", col4: "6PPA"}];
columnValues.forEach(obj => {
Object.keys(obj).forEach((key, index) => {
obj[columnNames[index]] = obj[key]
delete obj[key];
});
});
console.log(columnValues);