#javascript #arrays #jsonpath
#язык JavaScript #массивы #jsonpath
Вопрос:
Я использую путь JSON, чтобы сделать что-то подобное этому:
Я скопировал пример пути JSON, но изменил поле цены, чтобы оно представляло цену за год (число в массиве).
{ "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": [ 1, 2, 3 ] }, { "category" :"fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": [ 1, 2, 3 ] }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": [ 1, 2, 3 ] }, { "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": [ 1, 2, 3 ] } ], "bicycle": { "color": "red", "price": [ 1, 2, 3 ] } }, "expensive": 10 }
Что я хочу найти, так это общую стоимость всех книг за год.
Я могу получить массив массива (скажем, res), используя: $.store.book[*].price
Выход:
[ [ 1, 2, 3 ], [ 1, 2, 3 ], [ 1, 2, 3 ], [ 1, 2, 3 ] ]
Я хочу еще больше уменьшить этот результат (на сумму) до:
[4, 8, 12] // Sum up nth element of each array. // (res[0][0] res[1][0] res[2][0] res[3][0] = 4 ... and so on)
Есть ли способ добиться этого с помощью jsonpath (предпочтительно)/любого другого синтаксиса JavaScript ?
Ответ №1:
let data = [ [ 1, 7, 3 ], [ 2, 6, 3 ], [ 3, 5, 3 ], [ 4, 4, 3 ] ] let result = data[0].map((_, colIndex) =gt; data.map(row =gt; row[colIndex])) .map(value =gt; value.reduce((acc, value) =gt; acc value, 0)) console.log(result) // [ 10, 22, 12 ]
Первая карта транспонирует строки и столбцы, вторая карта суммирует то, что после транспонирования являются строками.
Ответ №2:
const data = { "store": { "book": [{ "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": [1, 2, 3] }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": [1, 2, 3] }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": [1, 2, 3] }, { "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": [1, 2, 3] } ] } } const prices = [] data.store.book.forEach(book =gt; { book.price.forEach((price, index) =gt; { if (!prices[index]) prices[index] = 0; prices[index] = price; }) }) console.log(prices)
Ответ №3:
Вы можете суммировать каждый из столбцов в матрице, сопоставив столбцы первой строки с уменьшением каждой из их последующих строк.
const data = {"store":{"book":[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":[1,2,3]},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":[1,2,3]},{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":[1,2,3]},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":[1,2,3]}],"bicycle":{"color":"red","price":[1,2,3]}},"expensive":10}; const sumColumns = (matrix) =gt; matrix[0].map((_, col) =gt; matrix.reduce((acc, data, row) =gt; acc data[col], 0)); const bookPrices = data.store.book.map(({ price }) =gt; price); const priceSums = sumColumns(bookPrices); console.log(priceSums); // [ 4, 8, 12 ]
.as-console-wrapper { top: 0; max-height: 100% !important; }
Ответ №4:
Вы можете использовать некоторые .map() и Array.prototype.reduce() в паре с оператором запятой.
const a = { "store": { "book": [{ "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": [1, 2, 3] }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": [1, 2, 3] }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": [1, 2, 3] }, { "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": [1, 2, 3] } ], "bicycle": { "color": "red", "price": [1, 2, 3] } }, "expensive": 10 }.store.book console.log(a.map(x=gt;x.price).reduce((x,y)=gt;(y.map((i,z)=gt;x[z] =y[z]),x)))