简体   繁体   English

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

[英]Form nested JSON object array from given JSON array

I have a json array of the form 我有一个形式的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'}]

I want the output as 我希望输出为

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

How to do it in Javascript/NodeJS? 如何在Javascript / NodeJS中执行此操作?

You could use an object as hash table and assign the values via the key with parts from from and to . 您可以将对象用作哈希表,并通过键将值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; } 

JS Fiddle: https://jsfiddle.net/6wqkhms3/1/ 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); 

Try the following code snippet - 尝试以下代码片段-

'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;
}, []);

 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); 

Using a simple loop to iterate through keys in a 'tmp' object which combined from 'from' and 'to' may help: 使用一个简单的循环遍历“ tmp”对象中从“ from”和“ to”组合的键可能会有所帮助:

            var input = [{'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 tmp = {};
            $.each(input, function (idx, obj) {
                var key = obj.from + obj.to
                tmp[key] = tmp[key] || { from: obj.from, to: obj.to};
                tmp[key].option = tmp[key].option || [];
                tmp[key].option.push(obj.option);
            });
            var output = [];
            for(var key in tmp)
            {
                output.push(tmp[key]);
            }

Wihtout jQuery, only javascript and cross browswer: 用jQuery,只有JavaScript和跨浏览器:

 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); 

You can use the below function unique to get the unique array out of the given array. 您可以使用下面的unique函数来从给定数组中获取唯一数组。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM