user3513872
user3513872

Reputation: 41

Create a new array by pushing json element and add new attribute in same pushed json object

Basically I have a json array and I want to create a new array in which I want to push all childNode and inside ChildNode its respective funding source name

var data = vardata={
  "costdata": [
    {
      fundingSource: 'A',
      childNode: [
        {
          childName: 'x',
          amt: 100
        }
      ]
    },
    {
      fundingSource: 'B',
      childNode: [
        {
          childName: 'y',
          amt: 200
        }
      ]
    }
  ]
}

Expected output is to create single json array and pushed funding source element inside respective childNode attributes

vardata={
  "costdata": [
    {
      childNode: [
        {
          fundingSource: 'A',
          childName: 'x',
          amt: 100
        }
      ]
    },
    {
      childNode: [
        {
          fundingSource: 'B',
          childName: 'y',
          amt: 200
        }
      ]
    }
  ]
}

Upvotes: 0

Views: 37

Answers (2)

kazington
kazington

Reputation: 78

If you just want to format object here is the solution:

var data = {
    "costdata": [
        {
            fundingSource: 'A',
            childNode: [
                {
                    childName: 'x',
                    amt: 100
                },
            ]
        },
        {
            fundingSource: 'B',
            childNode: [
                {
                    childName: 'y',
                    amt: 200
                }
            ]
        }
    ]
}

data["costdata"] = data["costdata"].map(el => {
    const fundingSource = el.fundingSource

    const updChildNode = el.childNode.map(child => {
        return {
            fundingSource,
            ...child
        }
    })
    return updChildNode
})

console.log(data)

Upvotes: 0

keval vaghasiya
keval vaghasiya

Reputation: 64

  var data = {
    "costdata": [
      {
        fundingSource: 'A',
        childNode: [
          {
            childName: 'x',
            amt: 100
          }
        ]
      },
      {
        fundingSource: 'B',
        childNode: [
          {
            childName: 'y',
            amt: 200
          }
        ]
      }
    ]
  }

let newData = [];
  for (let i = 0; i < data.costdata.length; i++) {
    const child = data.costdata[i];
    let childAry = [];
    if (child.childNode.length > 0) {
      childAry = [];
      for (let j = 0; j < child.childNode.length; j++) {
        const node = child.childNode[j];
        let dataObj = {
          fundingSource: child.fundingSource,
          childName: node.childName,
          amt: node.amt
        };
        childAry.push(dataObj);
      }
    }
    newData.push({ 'childNode': childAry });
  }
  console.log('newData==>', newData);

Here is a for loop to get your expected output

Upvotes: 1

Related Questions