Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
JS. How to copy array object per each prop

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"
        }
      ]
    }
  ];
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

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);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda