0

I have a JSON response and I need to flatten some objects according to conditions.

In my case, the condition is if object === "$"

I also need to flatten some array to string only. What is the best way to manage this? Any lib recommendations?

The final goal would be to use it as a GraphQL schema.

The JSON response is:

[
   {
      "$":{
         "product_id":"110015888426488829026466000222",
         "name":"Belstaff Trialmaster Pro W Motorradjacke Schwarz",
         "sku_number":"B000134394",
         "manufacturer_name":"BELSTAFF",
         "part_number":"42050011L81N03379005436"
      },
      "discount":[
         {
            "$":{
               "currency":"EUR"
            },
            "type":[
               "amount"
            ]
         }
      ],
      "price":[
         {
            "$":{
               "currency":"EUR"
            },
            "sale":[
               "1195.00"
            ],
            "retail":[
               "1195.00"
            ]
         }
      ],
      "shipping":[
         {
            "cost":[
               {
                  "$":{
                     "currency":"EUR"
                  },
                  "amount":[
                     "0.00"
                  ],
                  "currency":[
                     "EUR"
                  ]
               }
            ],
            "information":[
               "3–7 Werktage"
            ],
            "availability":[
               "in-stock"
            ]
         }
      ],
      "attributeClass":[
         {
            "$":{
               "class_id":"60"
            },
            "Product_Type":[
               "Motorcycle"
            ],
            "Size":[
               "36,38,40,42,44,46,48"
            ],
            "Material":[
               "Waxed Leather"
            ],
            "Color":[
               "Schwarz"
            ],
            "Gender":[
               "Female"
            ],
            "Age":[
               "Adult"
            ]
         }
      ]
   },
   ...
]

And I want

[
   {
      "product_id":"110015888426488829026466000222",
      "name":"Belstaff Trialmaster Pro W Motorradjacke Schwarz",
      "sku_number":"B000134394",
      "manufacturer_name":"BELSTAFF",
      "part_number":"42050011L81N03379005436"
      "discount":{
          "currency":"EUR"
          "type":"amount"
      },
      "price":{
         "currency": "EUR",
         "sale": "1195.00",
         "retail": "1195.00"
      },
      "shipping":[
         "cost":{
            "currency": "EUR"
            "amount": "0.00",
            "currency": "EUR"
         },
         "information":"3–7 Werktage",
         "availability": "in-stock"
      ],
      "attributeClass":{
         "class_id":"60",
         "Product_Type": "Motorcycle",
         "Size": "36,38,40,42,44,46,48",
         "Material": "Waxed Leather",
         "Color": "Schwarz",
         "Gender": "Female",
         "Age": "Adult"
      }
   },
   ...
]

What I tried:

const flatJson = async data => {
  try {
    const newData = await Promise.all(json.map( async (item, i) => {
      xxx
    }));
    return newData
  }
  catch(err) {
    console.log(err)
  }
};
4
  • do you have always only one object in the arrays? what should happen, if not? btw, what have you tried? Commented Apr 18, 2020 at 9:01
  • Cant you change your json response from backend to not include arrays for only single object? and make it clean? Commented Apr 18, 2020 at 9:10
  • @NinaScholz Yes, there is multiple object in the array. I edit my post with what I tried. Commented Apr 18, 2020 at 11:09
  • @Supercool. No, I don't have access to the backend Commented Apr 18, 2020 at 11:09

2 Answers 2

1

You could convert the various types to single objects.

const convert = object => {
    if (!object || typeof object !== 'object') return object;
    if (Array.isArray(object)) {
        return object.every(v => typeof v === 'string')
            ? object.join()
            : Object.assign({}, ...object.map(convert));
    }
    return Object.fromEntries(Object.entries(object).flatMap(([k, v]) =>
        k === '$'
            ? Object.entries(v).map(([k, v]) => [k, convert(v)])
            : [[k, convert(v)]]
    ));
};

var data = [{ $: { product_id: "110015888426488829026466000222", name: "Belstaff Trialmaster Pro W Motorradjacke Schwarz", sku_number: "B000134394", manufacturer_name: "BELSTAFF", part_number: "42050011L81N03379005436" }, discount: [{ $: { currency: "EUR" }, type: ["amount"] }], price: [{ $: { currency: "EUR" }, sale: ["1195.00"], retail: ["1195.00"] }], shipping: [{ cost: [{ $: { currency: "EUR" }, amount: ["0.00"], currency: ["EUR"] }], information: ["3–7 Werktage"], availability: ["in-stock"] }], attributeClass: [{ $: { class_id: "60" }, Product_Type: ["Motorcycle"], Size: ["36,38,40,42,44,46,48"], Material: ["Waxed Leather"], Color: ["Schwarz"], Gender: ["Female"], Age: ["Adult"] }] }],
    result = data.map(convert);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

0

You can try this recursion code

function recurseData(data, level) {
    var newdata = {};
    for(var prop in data) {
        if( data[prop].constructor == Object && prop=="$") {
            var data1 = recurseData(data[prop], level+1);
            for(var prop1 in data1)
                newdata[prop1] = data1[prop1];
        }
        else if(data[prop].constructor == Object){
            newdata[prop] = recurseData(data[prop],level+1);
        }
        else if(data[prop].constructor == Array && level > 0 && data[prop][0].constructor != Object && data[prop].length==1){
            newdata[prop] = data[prop][0];
        }
        else if(data[prop].constructor == Array) {
            newdata[prop] = [];
            for(var i=0;i<data[prop].length;i++)
                newdata[prop].push( recurseData(data[prop][i],level+1) );
        }
        else if(prop!="$")
            newdata[prop] = data[prop];
    }
    return newdata;
}

data[0] = recurseData(data[0], 0);

is simple loops through all tree structure and detects for a key $

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.