First Form:
You can create a custom function to format the data the way you want. In the example below, the function formatJSON
creates an object with two initial properties (timestamp
and revenue
). After that, a loop is made about the array custom_data
, adding the other 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 function formatJSON
, 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
, 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);
Like custom_data
is a array
, we can access a specific element using its index, through the notation array[index]
. To learn more, read that documentation about array
s on MDN.
Addendum:
Remember that to convert a string
for JSON (object
in Javascript), use:
JSON.parse('{ "hello": "world" }');
And to transform a JSON (object) into string
, utilize:
JSON.stringify({ hello: 'world' });
Reference:
Use
JSON.parse
to generate an object from the text, access the values in the formobjeto.atributo
assembling a new object the way you need it and finally useJSON.stringify
to convert the object to text. Want to try?– Woss
In custom_data always arrive two items or is it dynamic? it may be that N objects arrive?
– Luis Alberto Batista