Is there a way to remove from JSON but keep its content?

61 views Asked by At

I have a JSon like this :

[
  {
    "order_number": "",
    "products": [
      {
        "line_id": "" ,
        "cod_anf": "",
        "static_field_2": "",
        "nome_armazem": "",
        "cod_armazem": "",
        "gln": "",
        "sku_ah": "",
        "name": "",
        "qty": "",
        "_regular_price": "",
        "_sale_price": "",
        "line_total": "",
        "desconto": "",
        "pva": "",
        "category": "",
        "localidade": " ",
        "codigo_ah": " ",
        "Part of": ""
      },
      {
        "line_id": "",
        "cod_anf": "",
        "static_field_2": "",
        "nome_armazem": "",
      }
   ],

  {
    "order_number": "",
    "products": [
      {
        "line_id": 1,
        "cod_anf": "",
        "static_field_2": "",

I need to remove the "products" but keep it's content.

So the output should be like this:

Is it possible? I've tried and I cant make it work.

Thanks

2

There are 2 answers

0
Eldar On BEST ANSWER

You can use nested maps, spread operator, and flat function like below.

const json = [{
    "order_number": "2",
    "products": [{
        "line_id": "",
        "cod_anf": "",
        "static_field_2": "",
        "nome_armazem": "",
        "cod_armazem": "",
        "gln": "",
        "sku_ah": "",
        "name": "",
        "qty": "",
        "_regular_price": "",
        "_sale_price": "",
        "line_total": "",
        "desconto": "",
        "pva": "",
        "category": "",
        "localidade": " ",
        "codigo_ah": " ",
        "Part of": ""
      },
      {
        "line_id": "",
        "cod_anf": "",
        "static_field_2": "",
        "nome_armazem": "",
      }
    ]
  },

  {
    "order_number": "1",
    "products": [{
        "line_id": 1,
        "cod_anf": "",
        "static_field_2": "",
      }

    ]
  }
];

const flattened = json.map(r => [...r.products.map(q =>
    ({
      order_number: r.order_number,
      ...q
    })
  )])
  .flat(1);
console.log(flattened);

0
Gaurav Mogha On

Try this, assign json to data

let obj = [];

data.forEach(order =>{ 
  order.products.forEach(product => {
    obj.push({
      ...product,
      order_number: order.order_number
    })
  })
})