How to add new object into an arrays after map and check condition

Ach :

How can I add new object if value exist

const data = [
          { id: '30', mom: 'A', code: '0141', 'child':' Not used', 'status' :' X' },
          { id: '31', mom: 'B', code: '0141', 'child':' add Child', 'status' :' Y' }
          { id: '32', mom: 'B', code: '0141', 'child':' add child 2', 'status' :' Y' }
        ]

first I map data and if status = X I push new array if not I want to add new object key call child in to array that've status = X

 data.map((element, i) => {
  if (element.status == 'X') {
      arr.push({
          id: element.id,
          mom: element.mom,
          code: element.code
      });
  } else {
      // I want to add element child into arr that has status = X
      arr.push({ child: element.child });
  }
})

I want output like this

const arr = [
  { 
    id: '30', mom: 'A', code: '0141', 
    child: [
      'name':'add child',
      'name':'add child2'
    ]
  },
]
Fagner Sales :

Unfortunately, your code and your question is a little wrong and hard to understand. Array with key:value, status written with space. So... Sorry if understood it correctly.

This is what I understood

  • Create a new array with all elements with status X and put all child of elements with status Y in that array by the key child.

    const data = [
        { id: '30', mom: 'A', code: '0141', child: ' Not used', status: 'X' },
        { id: '31', mom: 'B', code: '0141', child: ' add Child', status: 'Y' },
        { id: '32', mom: 'B', code: '0141', child: ' add child 2', status: 'Y' }
    ];
    
    let objectX = data.filter(val => val.status == "X");
    objectX["child"] = data.filter(val => val.status == "Y").map(c => c.child);
    /*
    [
      { id: '30', mom: 'A', code: '0141', child: ' Not used', status: 'X' },
      child: [ ' add Child', ' add child 2' ]
    ]
    */
    console.log(objectX);
    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=18259&siteId=1
Recommended