I am faced with the challenge of creating a new object that combines keys from a specific array (const props = []
) and values from existing objects. If a key does not exist in an object, I aim to populate it with null
or placeholder values.
Here is my current code:
const props = ["name", "price", "qty", "category"]
let len = props.length;
const obj_1 = {
name: "Product_1",
price: 120,
category: 'phone'
}
const obj_2 = {
name: "Product_2",
price: 7893,
category: 'program_eq',
qty: 5
}
const final_obj = {
name: ["Product_1", "Product_2"],
price: [120, 7893],
category: ["phone", "program_eq"],
qty: [null, 5]
}
I have devoted significant time to finding a solution to this issue, and while I have a partial one, it only retrieves data from the first object. My approach involves using lodash/map to handle different types of collections.
You can find my tentative solution below:
const final_obj = {};
const props = ["name", "price", "qty", "category"];
let len = props.length;
const obj = {
c1s6c156a1cascascas: {
item: {
name: "Product_1",
price: 120,
category: "phone"
}
},
c454asc5515as41cas78: {
item: {
name: "Product_2",
price: 7893,
category: "program_eq",
qty: 5
}
}
};
_.map(obj, (element, key) => {
console.log(element.item);
while (len) {
let temp = props.shift();
let tempData = [];
if (element.item.hasOwnProperty([temp])) {
tempData.push(element.item[temp]);
} else {
tempData.push("---");
}
final_obj[temp] = tempData;
len--;
}
});
console.log(final_obj);
//
category:["phone"]
name:["Product_1"],
price:[120],
qty:["---"],