从给定的JSON数组中形成嵌套的JSON对象数组

时间:2016-09-23 06:46:17

标签: javascript json node.js

我有一个

形式的json数组
[{'from':'a','to':'b','type':'add','value':'100','op':'cr'},
{'from':'a','to':'b','type':'add','value':'200','op':'dr'},
{'from':'a','to':'b','type':'add','value':'300','op':'cr'},
{'from':'c','to':'d','type':'sub','value':'400','op':'dr'},
{'from':'c','to':'d','type':'sub','value':'500','op':'cr'}]

我希望输出为

[{'from':'a','to':'b','add':[{'100':'cr'},{'200':'dr'},{'300':'cr'}]},
 {'from':'c','to':'d','sub':[{'400':'dr'},{'500':'cr'}]}]

如何在Javascript / NodeJS中执行此操作?

7 个答案:

答案 0 :(得分:0)

您可以将对象用作哈希表,并通过密钥为fromto中的部分分配值。



var data = [{ from: 'a', to: 'b', option: '100' }, { from: 'a', to: 'b', option: '200' }, { from: 'a', to: 'b', option: '300' }, { from: 'c', to: 'd', option: '400' }, { from: 'c', to: 'd', option: '500' }],
    grouped = [];

data.forEach(function (a) {
    var key = [a.from, a.to].join('|');
    if (!this[key]) {
        this[key] = { from: a.from, to: a.to, option: [] };
        grouped.push(this[key]);
    }
    this[key].option.push(a.option);
}, Object.create(null));

console.log(grouped);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:0)

JS小提琴:https://jsfiddle.net/6wqkhms3/1/



var data = [{'from':'a','to':'b','option':'100'},
    {'from':'a','to':'b','option':'200'},
    {'from':'a','to':'b','option':'300'},
    {'from':'c','to':'d','option':'400'},
    {'from':'c','to':'d','option':'500'}];
    
    var out = [];
    
    // Utility function which finds-out if this object is available in the RESULT array or not
    function findObj(list, item) {
      var resultObj;
      for (var i in list) {
        if (list[i].from === item.from && list[i].to === item.to) {
          resultObj = list[i];
          break;
        }
      }
    
      return resultObj;
    }
    
    // EXECUTION
    for (var i in data) {

      // Check if this objec is available in the RESULT array,
      if (findObj(out, data[i])) {

        // If yes, then push the value to it
        findObj(out, data[i]).option.push(data[i].option);
      } else {
        // If NO, then add this item to the RESULT array
        out.push({
          from: data[i].from,
          to: data[i].to,
          option: [data[i].option]
        });
      }
    }
    
    console.log(out);




答案 2 :(得分:0)

请尝试以下代码段 -

'use strict';
var x = [{ 'from': 'a', 'to': 'b', 'option': '100' },
  { 'from': 'a', 'to': 'b', 'option': '200' },
  { 'from': 'a', 'to': 'b', 'option': '300' },
  { 'from': 'c', 'to': 'd', 'option': '400' },
  { 'from': 'c', 'to': 'd', 'option': '500' }
];

var match = false;

x.reduce(function(returnVal, item) {
  match = false;
  returnVal.map(function(each) {
    if (each.from === item.from && each.to === item.to) {
      if (Array.isArray(each.option)) {
        each.option.push(item.option);
      } else {
        each.option = [each.option];
        each.option.push(item.option);
      }
      match = true;
    }
    return each;
  })
  if (!match) {
    returnVal.push(item);
  }
  return returnVal;
}, []);

答案 3 :(得分:0)



var array1 = [
    {'from':'a','to':'b','option':'100'},
    {'from':'a','to':'b','option':'200'},
    {'from':'a','to':'b','option':'300'},
    {'from':'c','to':'d','option':'400'},
    {'from':'c','to':'d','option':'500'}
];

var array2 = [];

for(var i=0; i<array1.length; i++) {
    var obj = null,
        from = array1[i]['from'], 
        to = array1[i]['to'];

    for(var j=0; j<array2.length; j++) {
        if (array2[j]['from'] == from && array2[j]['to'] == to) {
            obj = array2[j];
            break;
        }
    }

    if (obj == null) {
        obj = {'from':from,'to':to,'option':[]};
        array2.push(obj);
    }

    obj['option'].push(array1[i]['option']);
}

console.log(array2);
&#13;
&#13;
&#13;

答案 4 :(得分:0)

使用一个简单的循环来迭代'tmp'对象中的键,这些键从'from'和'to'组合起来可能会有所帮助:

$ Press 1 to play or 2 to leave
> 1
You roll the dices
Dice 1: 5
Dice 2: 5
Dice 2
Your score is  12
Why it doesnt work :C 12

答案 5 :(得分:0)

没有jQuery,只有javascript和cross browswer:

var array = [
	{
		'from': 'a',
		'to': 'b',
		'option': '100'
	},
	{
		'from': 'a',
		'to': 'b',
		'option': '200'
	},
	{
		'from': 'a',
		'to': 'b',
		'option': '300'
	},
	{
		'from': 'c',
		'to': 'd',
		'option': '400'
	},
	{
		'from': 'c',
		'to': 'd',
		'option': '500'
	}
];

var array2 = [];
for (var a in array) {
	for (var b in array2) {
		if (array2[b].from == array[a].from && array2[b].to == array[a].to) {
			array2[b].option.push(array[a].option);
			break;
		}
	}
	
	if (!array2[b] || array2[b].option.indexOf(array[a].option) == -1) {
		array2.push({
			from: array[a].from,
			to: array[a].to,
			option: [array[a].option]
		});
	}
}

console.log(array2);

答案 6 :(得分:0)

您可以使用以下函数来获取给定数组中的唯一数组。

var array1 = [
{'from':'a','to':'b','option':'100'},
{'from':'a','to':'b','option':'200'},
{'from':'a','to':'b','option':'300'},
{'from':'c','to':'d','option':'400'},
{'from':'c','to':'d','option':'500'}
];


function unique(array) {
    var i = 0,
        map = {}, // This map object stores the objects of array1 uniquely
        uniqueArray = [],
        obj,
        len = array.length;

    for (i = 0; i < len; i++) {
       obj = array[i];
       from = obj.from; to = obj.to;
       // Create an id using from and to of the object
       id = from + '-' + to;
       // Check if object is already there in map object
       if (map[id]) {
            // If options is not an array then store the options in array
            map[id].option = map[id].option instanceof Array ? map[id].option : [map[id].option];
            map[id].option.push(obj.option);
       }
      // If object not available in map then create an object
       else {

            map[id] = {};
            map[id].from = obj.from;
            map[id].to = obj.to;
            map[id].option = obj.option;
            // Pushing the map object to the unique array
            uniqueArray.push(map[id]);
       }

    }
    return uniqueArray;
}