簡體   English   中英

如何在嵌套的 JSON 對象中查找和計算唯一值?

[英]How do i find and count unique values in nested JSON objects?

我有以下 JavaScript

{
  "business": [
{
  "order_contents": [
    {
      "id": 83,
      "name": "product 1",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 83,
      "name": "product 1",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 83,
      "name": "product 1",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 85,
      "name": "product 3",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 83,
      "name": "product 1",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 84,
      "name": "product 2",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 83,
      "name": "product 1",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 83,
      "name": "product 1",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 83,
      "name": "product 1",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 83,
      "name": "product 1",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 83,
      "name": "product 1",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 83,
      "name": "product 1",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    },
    {
      "id": 84,
      "name": "product 2",
      "price": "1.99",
      "quantity": 1,
      "total": "1.99",
      "ingredients": [],
      "extras": []
    }
   ]
  }
 ]
}

我想要完成的是,當訂單通過一個函數掃描 JSON 並創建一個具有每個唯一產品名稱的數組時,每次將數量加 1。

我曾嘗試使用 for 循環,但它循環了多次,但沒有在每個嵌套對象中找到名稱和值,它返回為 name = 0 並且該值是 main 中的單個嵌套對象目的。

像下面這樣的功能會起作用。 基本上,您將數組作為參數傳遞並返回一個對象,該對象 1) 如果該屬性尚不存在(例如產品 ID),則獲取一個新屬性,以及 2) 在該屬性確實存在時添加到項目計數中。 下面的函數生成如下輸出: {'product 1': 10, 'product 2': 1, 'product 3': 2}

function getItems(input) {
  var arr = input, obj = {};
  for (var i = 0; i < arr.length; i++) {
    if (!obj[arr[i].name]) {
      obj[arr[i].name] = 1;
    } else if (obj[arr[i].name]) {
      obj[arr[i].name] += 1;
    }
  }
  return obj;
}
// example use
console.log(getItems(order_contents)); // outputs entire object
console.log(getItems(order_contents)['product 1']); // outputs 10

看到您需要每個產品的唯一名稱...您可以將對象推送到一組對象中,然后將對象減少為單個唯一對象。

 var data={"business":[{"order_contents":[{"id":83,"name":"product 1","price":"1.99","quantity":1,"total":"1.99","ingredients":[],"extras":[]},{"id":83,"name":"product 1","price":"1.99","quantity":1,"total":"1.99","ingredients":[],"extras":[]},{"id":83,"name":"product 1","price":"1.99","quantity":1,"total":"1.99","ingredients":[],"extras":[]},{"id":85,"name":"product 3","price":"1.99","quantity":1,"total":"1.99","ingredients":[],"extras":[]},{"id":83,"name":"product 1","price":"1.99","quantity":1,"total":"1.99","ingredients":[],"extras":[]},{"id":84,"name":"product 2","price":"1.99","quantity":1,"total":"1.99","ingredients":[],"extras":[]},{"id":83,"name":"product 1","price":"1.99","quantity":1,"total":"1.99","ingredients":[],"extras":[]},{"id":83,"name":"product 1","price":"1.99","quantity":1,"total":"1.99","ingredients":[],"extras":[]},{"id":83,"name":"product 1","price":"1.99","quantity":1,"total":"1.99","ingredients":[],"extras":[]},{"id":83,"name":"product 1","price":"1.99","quantity":1,"total":"1.99","ingredients":[],"extras":[]},{"id":83,"name":"product 1","price":"1.99","quantity":1,"total":"1.99","ingredients":[],"extras":[]},{"id":83,"name":"product 1","price":"1.99","quantity":1,"total":"1.99","ingredients":[],"extras":[]},{"id":84,"name":"product 2","price":"1.99","quantity":1,"total":"1.99","ingredients":[],"extras":[]}]}]}; function buildData() { var items = data.business[0].order_contents, elems = [], groups = []; for( var i = 0; i < items.length; i++ ) { Array.prototype.push.call( elems, items[i] ); } groups.push( groupBy( elems, function( item ) { return item; } ) ); groupBy( groups, function( array ) { for( var i = 0; i < array.length; i++ ) { var obj = array[i].slice(); Object.keys( obj ).map( function( p ) { var length = obj.length; if( obj[p].hasOwnProperty( "quantity" ) ) { obj[p].quantity = length; } groups[i] = obj[p]; } ); } } ); function groupBy( array, f ) { var groups = {}; array.forEach( function( o ) { var group = JSON.stringify( f( o ) ); groups[group] = groups[group] || []; groups[group].push( o ); } ); return Object.keys( groups ).map( function( group ) { return groups[group]; } ); } return groups; } (function() { var old = console.log; var logger = document.getElementById( 'log' ); console.log = function( message ) { if( typeof message == 'object' ) { logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify( message, undefined, 2 ) : message) + '<br />'; } else { logger.innerHTML += message + '<br />'; } } })(); console.log( buildData() );
 <pre id="log"> </pre>

不喜歡重新發明輪子,所以這里是您如何使用對象掃描來回答您的問題

 // const objectScan = require('object-scan'); const counts = (haystack) => objectScan(['business[*].order_contents[*].name'], { filterFn: ({ value, context }) => { context[value] = (context[value] || 0) + 1; } })(haystack, {}); const data = { business: [{ order_contents: [{ id: 83, name: 'product 1', price: '1.99', quantity: 1, total: '1.99', ingredients: [], extras: [] }, { id: 83, name: 'product 1', price: '1.99', quantity: 1, total: '1.99', ingredients: [], extras: [] }, { id: 83, name: 'product 1', price: '1.99', quantity: 1, total: '1.99', ingredients: [], extras: [] }, { id: 85, name: 'product 3', price: '1.99', quantity: 1, total: '1.99', ingredients: [], extras: [] }, { id: 83, name: 'product 1', price: '1.99', quantity: 1, total: '1.99', ingredients: [], extras: [] }, { id: 84, name: 'product 2', price: '1.99', quantity: 1, total: '1.99', ingredients: [], extras: [] }, { id: 83, name: 'product 1', price: '1.99', quantity: 1, total: '1.99', ingredients: [], extras: [] }, { id: 83, name: 'product 1', price: '1.99', quantity: 1, total: '1.99', ingredients: [], extras: [] }, { id: 83, name: 'product 1', price: '1.99', quantity: 1, total: '1.99', ingredients: [], extras: [] }, { id: 83, name: 'product 1', price: '1.99', quantity: 1, total: '1.99', ingredients: [], extras: [] }, { id: 83, name: 'product 1', price: '1.99', quantity: 1, total: '1.99', ingredients: [], extras: [] }, { id: 83, name: 'product 1', price: '1.99', quantity: 1, total: '1.99', ingredients: [], extras: [] }, { id: 84, name: 'product 2', price: '1.99', quantity: 1, total: '1.99', ingredients: [], extras: [] }] }]}; console.log(counts(data)); // => { 'product 2': 2, 'product 1': 10, 'product 3': 1 }
 .as-console-wrapper {max-height: 100% !important; top: 0}
 <script src="https://bundle.run/object-scan@13.7.1"></script>

免責聲明:我是對象掃描的作者

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM