I have data in JSON format and it looks like this:
{
"book": [{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
}, {
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
}]
}
I want to extract only values corresponding to each object inside 'book' in form of array.
My output should look something like this:
[
"reference",
"Nigel Rees",
"Sayings of the Century",
8.95
],
[
"fiction",
"Evelyn Waugh",
"Sword of Honour",
12.99
]
Is there any way to do something like this using JSONPath Expression.
Just map the values of each object?
const data = {
"book": [{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
}, {
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
}]
};
const extractedValues = data.book.map(Object.values);
console.log(extractedValues);
.as-console-wrapper { top: 0; max-height: 100% !important; }
If you want to guarantee order, you could supply a key array:
const data = {
"book": [{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
}, {
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
}]
};
const extractValues = (arr, ...keys) => arr.map(obj => keys.map(key => obj[key]));
const extractedValues = extractValues(data.book, 'category', 'author', 'title', 'price');
console.log(extractedValues);
.as-console-wrapper { top: 0; max-height: 100% !important; }