Limitations:
id, and name when pushing to the desiredOutput array, but rather copying all the properties automatically.I have:
an array with one object which has multiple, unique, props
var items = [
{
id: 1,
name: "item name",
props: [
{
propId: 1,
propName: "name one"
},
{
propId: 2,
propName: "name two"
},
{
propId: 3,
propName: "name three"
}
]
}
];
Desired outcome:
a new array that contains one copy of the original object inside the array, per each prop
var desiredOutput = [
{
id: 1,
name: "item name",
props: [
{
propId: 1,
propName: "name one"
}
]
},
{
id: 1,
name: "item name",
props: [
{
propId: 2,
propName: "name two"
}
]
},
{
id: 1,
name: "item name",
props: [
{
propId: 3,
propName: "name three"
}
]
}
];
Logic
props.propsprops node in each object.props key and push it to final arrayvar items = [{
id: 1,
name: "item name",
props: [
{ propId: 1, propName: "name one" },
{ propId: 2, propName: "name two" },
{ propId: 3, propName: "name three" }
]
}];
var desiredOutput = [];
for (var index = 0; index < items.length; index++) {
var outputNode = {};
var entries = Object.entries(items[index]);
for(var innerIndex = 0; innerIndex < entries.length; innerIndex++) {
if(entries[innerIndex][0] !== 'props') {
outputNode[entries[innerIndex][0]] = entries[innerIndex][1];
}
}
for(var innerIndex = 0; innerIndex < items[index].props.length; innerIndex++) {
outputNode.props = [items[index].props[innerIndex]];
// This is mandatory to perform deep copy
desiredOutput.push(JSON.parse(JSON.stringify(outputNode)));
}
}
console.log(desiredOutput);
You can use something like this:
function copyProps(itemsArr) {
var copy = []; var i = 0;
itemsArr.forEach(function(item) {
item.props.forEach(function(prop) {
copy[i] = Object.assign({}, item);
copy[i].props = [Object.assign({}, prop)];
i++;
});
});
return copy;
}
just another way of getting the desired output with deep copy.
var items = [{
id: 1,
name: "item name",
props: [{
propId: 1,
propName: "name one"
}, {
propId: 2,
propName: "name two"
}, {
propId: 3,
propName: "name three"
}]
}];
var desiredOutput = [];
function ExtractDataFromProp(jsObject, jsObjectPropKey) {
if (Object.hasOwnProperty.call(jsObject, jsObjectPropKey)) {
const propElementValue = jsObject[jsObjectPropKey];
if (typeof propElementValue != "object") {
const propString = `"${jsObjectPropKey}" : ${isNaN(propElementValue) ? ("\"" + propElementValue + "\"") : propElementValue}`;
return propString;
}
return null;
}
}
items.forEach((item) => {
var itemObjArray = [];
var itemProps = [];
for (const itemKey in item)
itemObjArray.push(ExtractDataFromProp(item, itemKey));
item.props.forEach((prop) => {
for (const propKey in prop)
itemProps.push(ExtractDataFromProp(prop, propKey));
var finalObject = `{ ${itemObjArray.join(',').replace(/,\s*$/, "")}, "props": { ${itemProps.join(',').replace(/,\s*$/, "")} } }` //
desiredOutput.push(JSON.parse(finalObject))
});
});
console.dir(desiredOutput);