如果它们使用reduce,forEach或filter共享属性值,则组合JSON数组中的对象

时间:2016-02-09 22:43:59

标签: javascript arrays json

我已经在Stack上搜索了这个问题,但似乎无法找到答案。

我正在研究一个项目并尝试弄清楚如何减少JSON数组中的对象数量,并将共享值的对象中的// once everything is loaded, we run our Three.js stuff. $(function () { var geometry, material, mesha; var clock = new THREE.Clock(); var raycaster; var stats = initStats(); // create a scene, that will hold all our elements such as objects, cameras and lights. var scene = new THREE.Scene(); // create a camera, which defines where we're looking at. var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000); // create a render and set the size var webGLRenderer = new THREE.WebGLRenderer(); webGLRenderer.setClearColor(new THREE.Color(0x000, 1.0)); webGLRenderer.setSize(window.innerWidth, window.innerHeight); webGLRenderer.shadowMapEnabled = true; // position and point the camera to the center of the scene camera.position.x = 100; camera.position.y = 10; camera.position.z = 1000; camera.lookAt(new THREE.Vector3(0, 0, 0)); var camControls = new THREE.FirstPersonControls(camera); camControls.lookSpeed = 0.4; camControls.movementSpeed = 30; camControls.noFly = true; camControls.lookVertical = true; camControls.constrainVertical = false; camControls.verticalMin = 0.0; camControls.verticalMax = 1.0; camControls.lon = -150; camControls.lat = 120; var ambientLight = new THREE.AmbientLight(0x383838); scene.add(ambientLight); // add spotlight for the shadows var spotLight = new THREE.SpotLight(0xffffff); spotLight.position.set(100, 140, 130); spotLight.intensity = 10; scene.add(spotLight); // add the output of the renderer to the html element $("#WebGL-output").append(webGLRenderer.domElement); // call the render function var step = 0; // setup the control gui var controls = new function () { // we need the first child, since it's a multimaterial } var domEvents = new THREEx.DomEvents(camera, webGLRenderer.domElement) ////////////////////////////////////////////////////////////////////////////////// // add an object and make it move // ////////////////////////////////////////////////////////////////////////////////// var geometry = new THREE.SphereGeometry( 100.5 ) var material = new THREE.MeshNormalMaterial() var mesh = new THREE.Mesh( geometry, material ) scene.add( mesh ) ////////////////////////////////////////////////////////////////////////////////// // linkify our cube // ////////////////////////////////////////////////////////////////////////////////// var url = 'http://jeromeetienne.github.io/threex/' THREEx.Linkify(domEvents, mesh, url) domEvents.addEventListener(mesh, 'click', function(event){ console.log('you clicked on mesh', mesh) }, false) var gui = new dat.GUI(); var mesh; var onProgress = function ( xhr ) { if ( xhr.lengthComputable ) { var percentComplete = xhr.loaded / xhr.total * 100; console.log( Math.round(percentComplete, 2) + '% downloaded' ); } }; var onError = function ( xhr ) { }; var mtlLoader = new THREE.MTLLoader(); mtlLoader.setBaseUrl( '../assets/models/door/' ); mtlLoader.setPath( '../assets/models/door/' ); mtlLoader.load( 'door.mtl', function( materials ) { materials.preload(); var objLoader = new THREE.OBJLoader(); objLoader.setMaterials( materials ); objLoader.setPath( '../assets/models/door/' ); objLoader.load( 'door.obj', function ( object ) { object.position.y = -1; object.scale.x = 2; object.scale.y = 2; object.scale.z = 2; scene.add( object ); }, onProgress, onError ); }); // floor geometry = new THREE.PlaneGeometry( 2000, 2000, 100, 100 ); geometry.rotateX( - Math.PI / 2 ); for ( var i = 0, l = geometry.vertices.length; i < l; i ++ ) { var vertex = geometry.vertices[ i ]; vertex.x += Math.random() * 20 - 10; vertex.y += Math.random() * 3; vertex.z += Math.random() * 20 - 10; } for ( var i = 0, l = geometry.faces.length; i < l; i ++ ) { var face = geometry.faces[ i ]; face.vertexColors[ 0 ] = new THREE.Color().setHSL( Math.random() * 0.3 + 0.5, 0.75, Math.random() * 0.25 + 0.75 ); face.vertexColors[ 1 ] = new THREE.Color().setHSL( Math.random() * 0.3 + 10.5, 0.75, Math.random() * 0.25 + 0.75 ); face.vertexColors[ 2 ] = new THREE.Color().setHSL( Math.random() * 0.3 + 0.5, 0.75, Math.random() * 0.25 + 0.75 ); } material = new THREE.MeshBasicMaterial( { vertexColors: THREE.VertexColors } ); mesh = new THREE.Mesh( geometry, material ); scene.add( mesh ); function setCamControls() { } render(); function setRandomColors(object, scale) { var children = object.children; if (children && children.length > 0) { children.forEach(function (e) { setRandomColors(e, scale) }); } else { // no children assume contains a mesh if (object instanceof THREE.Mesh) { object.material.color = new THREE.Color(scale(Math.random()).hex()); if (object.material.name.indexOf("building") == 0) { object.material.emissive = new THREE.Color(0x444444); object.material.transparent = true; object.material.opacity = 0.8; } } } } function render() { stats.update(); var delta = clock.getDelta(); if (mesh) { // mesh.rotation.y+=0.006; } camControls.update(delta); webGLRenderer.clear(); // render using requestAnimationFrame requestAnimationFrame(render); webGLRenderer.render(scene, camera) } function initStats() { var stats = new Stats(); stats.setMode(0); // 0: fps, 1: ms // Align top-left stats.domElement.style.position = 'absolute'; stats.domElement.style.left = '0px'; stats.domElement.style.top = '0px'; $("#Stats-output").append(stats.domElement); return stats; } }); value结合起来使用name.reduce.forEach的属性,以便具有给定名称的所有值将配对在一起。我可以使用.filter和其他键控对象来执行此操作,但我希望将其保留为简单的JSON数组。我尝试了reducefilter的各种排列,但它们似乎又回归了奇怪的错误。

以下是我正在使用的JavaScript代码:

reduce

理想情况下,我希望有类似的内容:

//Json Data
var json = [{
    "name": "Value0",
    "value": "Sample0",
    "truthy": true
}, {
    "name": "Value0",
    "value": "Sample1",
    "truthy": false
}, {
    "name": "Value0",
    "value": "Sample2",
    "truthy": true
}, {
    "name": "Value0",
    "value": "Sample3",
    "truthy": false
}, {
    "name": "Value1",
    "value": "Sample4",
    "truthy": true
}, {
    "name": "Value1",
    "value": "Sample5",
    "truthy": false
}, {
    "name": "Value1",
    "value": "Sample6",
    "truthy": true
}, {
    "name": "Value1",
    "value": "Sample7",
    "truthy": false
}, {
    "name": "Value2",
    "value": "Sample8",
    "truthy": true
}, {
    "name": "Value2",
    "value": "Sample9",
    "truthy": false
}, {
    "name": "Value2",
    "value": "Sample10",
    "truthy": true
}, {
    "name": "Value2",
    "value": "Sample11",
    "truthy": false
}, {
    "name": "Value3",
    "value": "Sample12",
    "truthy": true
}, {
    "name": "Value3",
    "value": "Sample13",
    "truthy": false
}, {
    "name": "Value3",
    "value": "Sample14",
    "truthy": true
}, {
    "name": "Value3",
    "value": "Sample15",
    "truthy": false
}, {
    "name": "Value4",
    "value": "Sample16",
    "truthy": true
}, {
    "name": "Value4",
    "value": "Sample17",
    "truthy": false
}, {
    "name": "Value4",
    "value": "Sample18",
    "truthy": true
}, {
    "name": "Value4",
    "value": "Sample19",
    "truthy": false
}, {
    "name": "Value5",
    "value": "Sample20",
    "truthy": true
}, {
    "name": "Value5",
    "value": "Sample21",
    "truthy": false
}, {
    "name": "Value5",
    "value": "Sample22",
    "truthy": true
}, {
    "name": "Value5",
    "value": "Sample23",
    "truthy": false
}, {
    "name": "Value6",
    "value": "Sample24",
    "truthy": true
}, {
    "name": "Value6",
    "value": "Sample25",
    "truthy": false
}, {
    "name": "Value6",
    "value": "Sample26",
    "truthy": true
}, {
    "name": "Value6",
    "value": "Sample27",
    "truthy": false
}, {
    "name": "Value7",
    "value": "Sample28",
    "truthy": true
}, {
    "name": "Value7",
    "value": "Sample29",
    "truthy": false
}, {
    "name": "Value7",
    "value": "Sample30",
    "truthy": true
}, {
    "name": "Value7",
    "value": "Sample31",
    "truthy": false
}, {
    "name": "Value8",
    "value": "Sample32",
    "truthy": true
}, {
    "name": "Value8",
    "value": "Sample33",
    "truthy": false
}, {
    "name": "Value8",
    "value": "Sample34",
    "truthy": true
}, {
    "name": "Value8",
    "value": "Sample35",
    "truthy": false
}, {
    "name": "Value9",
    "value": "Sample36",
    "truthy": true
}, {
    "name": "Value9",
    "value": "Sample37",
    "truthy": false
}, {
    "name": "Value9",
    "value": "Sample38",
    "truthy": true
}, {
    "name": "Value9",
    "value": "Sample39",
    "truthy": false
}, {
    "name": "Value10",
    "value": "Sample40",
    "truthy": true
}, {
    "name": "Value10",
    "value": "Sample41",
    "truthy": false
}, {
    "name": "Value10",
    "value": "Sample42",
    "truthy": true
}, {
    "name": "Value10",
    "value": "Sample43",
    "truthy": false
}, {
    "name": "Value11",
    "value": "Sample44",
    "truthy": true
}, {
    "name": "Value11",
    "value": "Sample45",
    "truthy": false
}, {
    "name": "Value11",
    "value": "Sample46",
    "truthy": true
}, {
    "name": "Value11",
    "value": "Sample47",
    "truthy": false
}, {
    "name": "Value12",
    "value": "Sample48",
    "truthy": true
}, {
    "name": "Value12",
    "value": "Sample49",
    "truthy": false
}, {
    "name": "Value12",
    "value": "Sample50",
    "truthy": true
}, {
    "name": "Value12",
    "value": "Sample51",
    "truthy": false
}, {
    "name": "Value13",
    "value": "Sample52",
    "truthy": true
}, {
    "name": "Value13",
    "value": "Sample53",
    "truthy": false
}, {
    "name": "Value13",
    "value": "Sample54",
    "truthy": true
}, {
    "name": "Value13",
    "value": "Sample55",
    "truthy": false
}, {
    "name": "Value14",
    "value": "Sample56",
    "truthy": true
}, {
    "name": "Value14",
    "value": "Sample57",
    "truthy": false
}, {
    "name": "Value14",
    "value": "Sample58",
    "truthy": true
}, {
    "name": "Value14",
    "value": "Sample59",
    "truthy": false
}, {
    "name": "Value15",
    "value": "Sample60",
    "truthy": true
}, {
    "name": "Value15",
    "value": "Sample61",
    "truthy": false
}, {
    "name": "Value15",
    "value": "Sample62",
    "truthy": true
}, {
    "name": "Value15",
    "value": "Sample63",
    "truthy": false
}, {
    "name": "Value16",
    "value": "Sample64",
    "truthy": true
}, {
    "name": "Value16",
    "value": "Sample65",
    "truthy": false
}, {
    "name": "Value16",
    "value": "Sample66",
    "truthy": true
}, {
    "name": "Value16",
    "value": "Sample67",
    "truthy": false
}, {
    "name": "Value17",
    "value": "Sample68",
    "truthy": true
}, {
    "name": "Value17",
    "value": "Sample69",
    "truthy": false
}, {
    "name": "Value17",
    "value": "Sample70",
    "truthy": true
}, {
    "name": "Value17",
    "value": "Sample71",
    "truthy": false
}, {
    "name": "Value18",
    "value": "Sample72",
    "truthy": true
}, {
    "name": "Value18",
    "value": "Sample73",
    "truthy": false
}, {
    "name": "Value18",
    "value": "Sample74",
    "truthy": true
}, {
    "name": "Value18",
    "value": "Sample75",
    "truthy": false
}, {
    "name": "Value19",
    "value": "Sample76",
    "truthy": true
}, {
    "name": "Value19",
    "value": "Sample77",
    "truthy": false
}, {
    "name": "Value19",
    "value": "Sample78",
    "truthy": true
}, {
    "name": "Value19",
    "value": "Sample79",
    "truthy": false
}, {
    "name": "Value20",
    "value": "Sample80",
    "truthy": true
}, {
    "name": "Value20",
    "value": "Sample81",
    "truthy": false
}, {
    "name": "Value20",
    "value": "Sample82",
    "truthy": true
}, {
    "name": "Value20",
    "value": "Sample83",
    "truthy": false
}, {
    "name": "Value21",
    "value": "Sample84",
    "truthy": true
}, {
    "name": "Value21",
    "value": "Sample85",
    "truthy": false
}, {
    "name": "Value21",
    "value": "Sample86",
    "truthy": true
}, {
    "name": "Value21",
    "value": "Sample87",
    "truthy": false
}, {
    "name": "Value22",
    "value": "Sample88",
    "truthy": true
}, {
    "name": "Value22",
    "value": "Sample89",
    "truthy": false
}, {
    "name": "Value22",
    "value": "Sample90",
    "truthy": true
}, {
    "name": "Value22",
    "value": "Sample91",
    "truthy": false
}, {
    "name": "Value23",
    "value": "Sample92",
    "truthy": true
}, {
    "name": "Value23",
    "value": "Sample93",
    "truthy": false
}, {
    "name": "Value23",
    "value": "Sample94",
    "truthy": true
}, {
    "name": "Value23",
    "value": "Sample95",
    "truthy": false
}, {
    "name": "Value24",
    "value": "Sample96",
    "truthy": true
}, {
    "name": "Value24",
    "value": "Sample97",
    "truthy": false
}, {
    "name": "Value24",
    "value": "Sample98",
    "truthy": true
}, {
    "name": "Value24",
    "value": "Sample99",
    "truthy": false
}];
//removing irrelevant data items
json = json.map(function(item) {
    return {
        "name": item.name,
        "values": [item.value]
    };
});
//attempt at reduce function 

json.reduce(function(p, c) {
    if (p && p.name === c.name) {
        p.value.push(c.value);
    }
});
/*
//attempt at filter function
json = json.filter(function(item,i) {
if (i > 0 && item.name === json[i-1].name) {
json[i-1].value.push(item.name);
}
});

//forEach attempt /*
json = json.forEach(function(item, i, arr) {
  if (i > 0) {
    if (arr[i].name === arr[i - 1].name) {
      var pop = json.pop();
      json[i - 1].value.push(pop.value);
    }
  }
});
*/


console.log(JSON.stringify(json));

2 个答案:

答案 0 :(得分:1)

不是最优雅的解决方案,但应该按照您的要求完全正常工作

var w = canvas.width * 4;
var r,g,b;

for (var i=0; i<canvas.width * 4; i+=4) {
  for (var j=0; j<canvas.height; j+=1) {
        //console.log(j*w+i, j*w+i+1, j*w+i+2, j*w+i+3);
    r = imdata[j*w+i]
            g = imdata[j*w+i+1];
            b = imdata[j*w+i+2];

    if ((r >= 164 && r <= 255) && 
        (g >= 191 && g <= 229) && 
        (b >= 220 && b <= 255)) {

      // blue  = water
      imdata[j*w+i] = 0;
      imdata[j*w+i+1] = 0;
      imdata[j*w+i+2] = 150;

    } else {

      // green = land
      imdata[j*w+i] = 0;
      imdata[j*w+i+1] = 120;
      imdata[j*w+i+2] = 0;                      
    }                   
  }
}

另外,小提琴:https://jsfiddle.net/6xph0g9b/

答案 1 :(得分:0)

最简单的想法分两个阶段:1)如何过滤我需要的数据?然后2)如何将其缩小为我想要的格式?

要完成#1,您可以使用filter函数,它看起来像:

json.filter((el) => el.truthy)

这将返回一个新数组,其中包含truthytrue的所有元素。然后,将它们打包成名称/值对,通过reduce

运行它们
json.filter((el) => el.truthy).reduce((seen, el) => {
  if(!seen[el.name]) seen[el.name] = []; // If our initial state doesn't have a key for this element's name, then initialize it to an empty array.
  if(seen[el.name].indexOf(el.value) === -1) // If our state doesn't already contain this element's value, then add it.
    seen[el.name].push(el.value);
  return seen; // Return state
}, {} /* Initial state is an empty object */)

这会生成一个对象,其密钥为el.name(例如:Value0),其值为所有Value0&#39; value字段的数组(例如:Sample0和{ {1}})。

这会让你走上正轨吗?