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"
}
]
}
];
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 = []; for (var index = 0; index < items.length; index++) { for(var innerIndex = 0; innerIndex < items[index].props.length; innerIndex++) { desiredOutput.push({ id: items[index].id, name: items[index].name, props: [items[index].props[innerIndex]] }) } } console.log(desiredOutput);
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);
You can use something like this:
function copyProps(items) {
var copy = [], i=0;
items.forEach(function(item) {
item.props.forEach(function(prop) {
copy[i++] = { id: item.id, name: item.name, prop: [Object.assign({}, prop)]}
})
});
return copy;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.