First Form:
You can create a custom function to format the data any way you want. In the example below, the formatJSON
function creates an object with two initial properties ( timestamp
and revenue
). After that, a loop is made on the array custom_data
, adding the remaining values to the object.
const first = {
event: 'comprou',
timestamp: '2016-09-22T13:57:31.2311892-03:00',
revenue: 250,
custom_data: [
{
key: 'store_name',
value: 'Patio Savassi'
},
{
key: 'transaction_id',
value: '3029384'
}
]
};
function formatJSON (data) {
const object = {
timestamp: data.timestamp,
revenue: data.revenue
};
for (const customData of data.custom_data) {
object[customData.key] = customData.value;
}
return object;
}
console.log(formatJSON(first));
Note that to shorten the code, we can rewrite the formatJSON
function, using a new JavaScript feature called destructuring >:
function formatJSON ({ timestamp, revenue, custom_data: data }) {
const object = { timestamp, revenue };
for (const { key, value } of data) {
object[key] = value;
}
return object;
}
Second form:
If you simply want to access the properties store_name
and transaction_id
, you can do so:
const oldObject = {
event: 'comprou',
timestamp: '2016-09-22T13:57:31.2311892-03:00',
revenue: 250,
custom_data: [
{
key: 'store_name',
value: 'Patio Savassi'
},
{
key: 'transaction_id',
value: '3029384'
}
]
};
const newObject = {
timestamp: oldObject.timestamp,
revenue: oldObject.revenue,
store_name: oldObject.custom_data[0].value,
transaction_id: oldObject.custom_data[1].value
};
console.log(newObject);
Since custom_data
is a array
, we can access a specific element using its index, using the array[index]
notation. To learn more, read this documentation over% with% s in MDN .
Addendum:
Remember that to convert a array
to JSON (% with% in JavaScript), use:
JSON.parse('{ "hello": "world" }');
And to transform a JSON (object) into string
, use:
JSON.stringify({ hello: 'world' });
Reference: