Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Object Tranformation

I am using the map to transforming the JSON. Instead of Single object, I am getting an Array of data. Snipt Shown Below.

I am trying to achieve following JSON

{
  "data": {
    "test1": {
        "abc": {
            "size": "big",
            "id": "1"
        }
    },
    "test2": {
        "abc": {
            "size": "small",
            "id": "2"
        }
    }
  }
}

But getting following JSON

{
"data": [{
    "test1": {
        "abc": {
            "size": "big",
            "id": "1"
        }
    }
}, {
    "test2": {
        "abc": {
            "size": "big",
            "id": "2"
        }
    }
}]

}

Here is my code.

const test = [{ id: 'ddec9c7f-95aa-4d07-a45a-dcdea96309a9',
  ad_id: 'test1',
  country: 'ID',
  abc: { size: 'big', id: '1' },
},
{ id: 'ddec9c7f-95aa-4d07-a45a-dcdea96309a9',
  ad_id: 'test2',
  country: 'ID',
  abc: { size: 'small', id: '2' },
},
];
const transformedTest = test.map(result =>
  ({ [result.ad_id]: { abc: result.abc } }));

const data = { data: transformedTest };
console.log(JSON.stringify(data));

Any help will be appreciated

like image 571
user11229655 Avatar asked Jun 07 '26 06:06

user11229655


2 Answers

Try this:

const test =  [
  {
    "id": "ddec9c7f-95aa-4d07-a45a-dcdea96309a9",
    "ad_id": "test1",
    "country": "ID",
    "abc": {
      "size": "big",
      "id": "1"
    }
  },
  {
    "id": "ddec9c7f-95aa-4d07-a45a-dcdea96309a9",
    "ad_id": "test2",
    "country": "ID",
    "abc": {
      "size": "big",
      "id": "2"
    }
  }
];
const result  = test.reduce((acc,{ad_id, abc})=> (acc.data[ad_id] = {abc}, acc),{data:{}}) 

console.log(result);
like image 100
Ghoul Ahmed Avatar answered Jun 10 '26 04:06

Ghoul Ahmed


const transformedTest = test.reduce((pv, result) =>
({...pv, [result.ad_id]: { abc: result.abc } }), {});
like image 42
Tor Brekke Skjøtskift Avatar answered Jun 10 '26 02:06

Tor Brekke Skjøtskift