Home > other >  JS. How to copy array object per each prop
JS. How to copy array object per each prop

Time:11-20

Limitations:

  1. I am limited to not using ES6 syntax
  2. I need a way to do this without knowing the exact properties of the object. So without manually adding 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"
        }
      ]
    }
  ];

CodePudding user response:

Logic

  • Loop through keys each item in items array.
  • Check if the key name is not props.
  • Add the key value combination to an object except for key props
  • Loop through the props node in each object.
  • Add each prop to props key and push it to final array
  • You should perform a deep copy logic here, sice you are keep on updating the pushong object

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  ) {
  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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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;
}

CodePudding user response:

just another way of getting the desired output.

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);
  • Related