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

时间:2014-12-26 00:04:17

标签: javascript

我有以下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并创建一个包含每个唯一产品名称的数组时,每次都会增加数量。

我尝试过使用for循环,但它循环了它的次数,但是没有找到每个嵌套对象中的名称和值,它返回名称= 0,值为个体主对象内的嵌套对象。

3 个答案:

答案 0 :(得分:2)

像下面这样的功能会起作用。基本上,您将数组作为参数传递,并返回一个对象: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

答案 1 :(得分:0)

看到每个产品都需要唯一的名称......您可以将对象推送到 分组的对象数组 ,然后将对象缩减为单个唯一对象。

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>

答案 2 :(得分:0)

不是重新发明轮子的忠实拥护者,所以这里是您如何使用object-scan来回答您的问题

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 }