skip to Main Content

I have this JSON response, I want to unflatten it, but every possible unflatten library just append it to array, I want to highlight to have 3 object like shown, is there any easier way?

{
    "highlights.id": ["9ab80883-e8eb-4710-9818-e476fc32e356", "824ff2a0-1f17-44b7-b99f-ce227af12ea7", "4a9e35c5-e03f-41d6-a4b5-635b08bc1bbe", ],
    "highlights.key": ["0", "1", "2"],
    "highlights.value": ['16" Pedestal Fan', "High Quality Metal Grill ", "Heavy Duty Motor with 2000 RPM", ],
    "highlights.productId": ["655ea6af-9e5c-401e-b317-ea1fac55857f", "655ea6af-9e5c-401e-b317-ea1fac55857f", "655ea6af-9e5c-401e-b317-ea1fac55857f", ],
    "highlights.createdAt": ["2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", ],
    "highlights.updatedAt": ["2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", ]
}

I want something like

highlights:[ {// id, key, value, productId}, {}, {}]

But I’m getting

highlights:{ id:[], productId:[], key:[], value:[]

4

Answers


  1. Use Array.map

    You can use .map function to loop through the keys just to make it consistent and return a new object, the way you want it, then store in to the new highlights array.

    DEMO

    var jsonObject = { "highlights.id": [     "9ab80883-e8eb-4710-9818-e476fc32e356",     "824ff2a0-1f17-44b7-b99f-ce227af12ea7",     "4a9e35c5-e03f-41d6-a4b5-635b08bc1bbe",   ],   "highlights.key": ["0", "1", "2"],   "highlights.value": [     '16" Pedestal Fan',     "High Quality Metal Grill ",     "Heavy Duty Motor with 2000 RPM",   ],   "highlights.productId": [     "655ea6af-9e5c-401e-b317-ea1fac55857f",     "655ea6af-9e5c-401e-b317-ea1fac55857f",     "655ea6af-9e5c-401e-b317-ea1fac55857f",   ],   "highlights.createdAt": [     "2023-03-15T07:27:39.150Z",     "2023-03-15T07:27:39.150Z",     "2023-03-15T07:27:39.150Z",   ],   "highlights.updatedAt": [     "2023-03-15T07:27:39.150Z",     "2023-03-15T07:27:39.150Z",     "2023-03-15T07:27:39.150Z",   ] };
    
    const highlights = jsonObject['highlights.key'].map((v, i) => {
        return {
            "id": jsonObject['highlights.id'][i],
            "key": jsonObject['highlights.key'][i],
            "value": jsonObject['highlights.value'][i],
            "productId": jsonObject['highlights.productId'][i],
            "createdAt": jsonObject['highlights.createdAt'][i],
            "updatedAt": jsonObject['highlights.updatedAt'][i],
        };
    })
    console.log(highlights);

    Dynamic solution:

    If you want it to be more dynamic you can loop through the keys of your JSON object as well

    var jsonObject = { "highlights.id": [     "9ab80883-e8eb-4710-9818-e476fc32e356",     "824ff2a0-1f17-44b7-b99f-ce227af12ea7",     "4a9e35c5-e03f-41d6-a4b5-635b08bc1bbe",   ],   "highlights.key": ["0", "1", "2"],   "highlights.value": [     '16" Pedestal Fan',     "High Quality Metal Grill ",     "Heavy Duty Motor with 2000 RPM",   ],   "highlights.productId": [     "655ea6af-9e5c-401e-b317-ea1fac55857f",     "655ea6af-9e5c-401e-b317-ea1fac55857f",     "655ea6af-9e5c-401e-b317-ea1fac55857f",   ],   "highlights.createdAt": [     "2023-03-15T07:27:39.150Z",     "2023-03-15T07:27:39.150Z",     "2023-03-15T07:27:39.150Z",   ],   "highlights.updatedAt": [     "2023-03-15T07:27:39.150Z",     "2023-03-15T07:27:39.150Z",     "2023-03-15T07:27:39.150Z",   ] };
    const highlights = jsonObject['highlights.key'].map((v, i) => {
        const newObject = {};
        Object.keys(jsonObject).forEach((v) => {
            newObject[v.replace('highlights.','')] = jsonObject[v][i];
        });
        return newObject;
    })
    console.log(highlights);
    Login or Signup to reply.
  2. Sorry but it’s not possible to convert into

    highlights:[ {// id, key, value, productId}, {}, {}]
    

    because there is an object inside your array highlights. You must declare an object key. I have an idea for your solution by using Class and constructor

    var object = {
      "highlights.id": ["9ab80883-e8eb-4710-9818-e476fc32e356", "824ff2a0-1f17-44b7-b99f-ce227af12ea7", "4a9e35c5-e03f-41d6-a4b5-635b08bc1bbe", ],
      "highlights.key": ["0", "1", "2"],
      "highlights.value": ['16" Pedestal Fan', "High Quality Metal Grill ", "Heavy Duty Motor with 2000 RPM", ],
      "highlights.productId": ["655ea6af-9e5c-401e-b317-ea1fac55857f", "655ea6af-9e5c-401e-b317-ea1fac55857f", "655ea6af-9e5c-401e-b317-ea1fac55857f", ],
      "highlights.createdAt": ["2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", ],
      "highlights.updatedAt": ["2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", ]
    }
    var arr = []
    
    class Highlights {
      constructor(id, key, value, productId, createdAt, updatedAt) {
        this.id = id;
        this.key = key;
        this.value = value;
        this.productId = productId;
        this.createdAt = createdAt;
        this.updatedAt = updatedAt
      }
    }
    
    for (i = 0; i < object["highlights.id"].length; i++) {
      let highlights = new Highlights(object["highlights.id"][i], object["highlights.key"][i], object["highlights.value"][i],
        object["highlights.productId"][i], object["highlights.createdAt"][i], object["highlights.updatedAt"][i])
    
      arr.push(highlights);
    }
    //get all 
    console.log(arr)
    //get arr 0 ID
    console.log(arr[0].id);

    If you meant

    highlights:[ {id:"a", key: "b", value: "c", productId: "d"}, {}, {}]
    

    then my solution to you is…

    var object = {
      "highlights.id": ["9ab80883-e8eb-4710-9818-e476fc32e356", "824ff2a0-1f17-44b7-b99f-ce227af12ea7", "4a9e35c5-e03f-41d6-a4b5-635b08bc1bbe", ],
      "highlights.key": ["0", "1", "2"],
      "highlights.value": ['16" Pedestal Fan', "High Quality Metal Grill ", "Heavy Duty Motor with 2000 RPM", ],
      "highlights.productId": ["655ea6af-9e5c-401e-b317-ea1fac55857f", "655ea6af-9e5c-401e-b317-ea1fac55857f", "655ea6af-9e5c-401e-b317-ea1fac55857f", ],
      "highlights.createdAt": ["2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", ],
      "highlights.updatedAt": ["2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", ]
    }
    var arr = []
    for (i = 0; i < object["highlights.id"].length; i++) {
      arr.push({
        id: object["highlights.id"][i],
        key: object["highlights.key"][i],
        value: object["highlights.value"][i],
        productId: object["highlights.productId"][i],
        createdAt: object["highlights.createdAt"][i],
        updatedAt: object["highlights.updatedAt"][i]
      });
    }
    //get all arr
    console.log(arr)
    //get arr 0 ID
    console.log(arr[0].id)
    //or
    console.log(arr[0]["id"])

    The difference between class and object in this use case is naming convention such that object allows you to use spacing for naming key while you can’t do that in constructor (either _ or capital keys to make it easier to differentiate)

    Login or Signup to reply.
  3. NOTE : While updating object in javascript, [.] where . is dynamic key without square bracket it will be a static key.

    let flattenHighlights = []
    let flattenKeysObject = {}
    for(let key of Object.keys(highlights)){
         let highlightKey = key.replace('highlights.','')
         {...flattenKeysObject, [highlightKey]:highlights[key]}
    }
    console.log("highlights : ", flattenKeysObject)
    
    Login or Signup to reply.
  4. You can do it with iterate it through data array. If you want a simple answer, try this:

    1. First way:
    let data = {
        "highlights.id": ["9ab80883-e8eb-4710-9818-e476fc32e356", "824ff2a0-1f17-44b7-b99f-ce227af12ea7", "4a9e35c5-e03f-41d6-a4b5-635b08bc1bbe", ],
        "highlights.key": ["0", "1", "2"],
        "highlights.value": ['16" Pedestal Fan', "High Quality Metal Grill ", "Heavy Duty Motor with 2000 RPM", ],
        "highlights.productId": ["655ea6af-9e5c-401e-b317-ea1fac55857f", "655ea6af-9e5c-401e-b317-ea1fac55857f", "655ea6af-9e5c-401e-b317-ea1fac55857f", ],
        "highlights.createdAt": ["2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", ],
        "highlights.updatedAt": ["2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", ]
    }
    
    let newData = Array(data['highlights.id'].length).fill(null).map((d,index) => ({
      id: data['highlights.id'][index],
      key: data['highlights.key'][index],
      value: data['highlights.value'][index],
      productId: data['highlights.productId'][index],
    //  createdAt: data['highlights.updatedAt'][index],
    //  updatedAt: data['highlights.updatedAt'][index]
    }));
    console.log(newData);

    1. Second way:
    let data = {
        "highlights.id": ["9ab80883-e8eb-4710-9818-e476fc32e356", "824ff2a0-1f17-44b7-b99f-ce227af12ea7", "4a9e35c5-e03f-41d6-a4b5-635b08bc1bbe", ],
        "highlights.key": ["0", "1", "2"],
        "highlights.value": ['16" Pedestal Fan', "High Quality Metal Grill ", "Heavy Duty Motor with 2000 RPM", ],
        "highlights.productId": ["655ea6af-9e5c-401e-b317-ea1fac55857f", "655ea6af-9e5c-401e-b317-ea1fac55857f", "655ea6af-9e5c-401e-b317-ea1fac55857f", ],
        "highlights.createdAt": ["2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", ],
        "highlights.updatedAt": ["2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", "2023-03-15T07:27:39.150Z", ]
    }
    
    let newData = Array(data['highlights.id'].length).fill(null).map((d,index) => {
      let obj = {};
      Object.keys(data).forEach((key) => {
        obj[key.split('.')[1]] = data[key][index];
      });
      return obj;
    }).map((d)=>{
      delete d['createdAt'];
      delete d['updatedAt'];
      return d;
    });
    console.log(newData);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search