用于添加多个项目的循环JavaScript

时间:2018-11-19 05:50:39

标签: javascript arrays

我的最终目标是一个类似于以下数组的数组:

let nodes_data =  [
    {"id": "A", "depth": 1, "x":50, "y":100},
    {"id": "B", "depth": 2, "x":150, "y":200},
    {"id": "C", "depth": 2, "x":250, "y":200},
    {"id": "D", "depth": 3, "x":350, "y":300},
] 

但是,我仅从id和depth开始,我想分别计算x和y。

因此,给定起始源数组:

let nodes_data =  [
    {"id": "A", "depth": 1},
    {"id": "B", "depth": 2},
    {"id": "C", "depth": 2},
    {"id": "D", "depth": 3},
]

我试图做一个for循环添加到数组中:

 function presetCoordinates(data){
 let nodes = [];
  for ( let i = 0; i< nodes_data.length; i++) {
    y = data[i].depth*100;
    x = (i*100) + 50;

    nodes.push(x, y)
  }
  return nodes;
}

let nodes_with_coords = presetCoordinates(nodes_data)
console.log(nodes_with_coords) 

nodes_with_coords是我的“目标”数组。

但是我得到了一些非常奇怪的结果。对我在这里缺少什么有任何想法吗?我想也许我把这个复杂化了。

4 个答案:

答案 0 :(得分:1)

您不包括原始对象:

function presetCoordinates(data) {
  let nodes = [];
  for (let i = 0; i < nodes_data.length; i++) {
    y = data[i].depth * 100;
    x = (i * 100) + 50;
    
    // include the contents of the original node using spread
    nodes.push({ ...data[i], x, y }) 
  }
  return nodes;
}

let nodes_data =  [
    {"id": "A", "depth": 1},
    {"id": "B", "depth": 2},
    {"id": "C", "depth": 2},
    {"id": "D", "depth": 3},
]

let nodes_with_coords = presetCoordinates(nodes_data)
console.log(nodes_with_coords)

答案 1 :(得分:0)

您可以像下面这样使用“ Array.map”。

地图的作用是,它循环遍历“ nodes_data”中的每个元素,并返回您需要的新对象/数组/ {任何内容},在这种情况下,新对象将包含更多数据。

let nodes_data =  [
    {"id": "A", "depth": 1},
    {"id": "B", "depth": 2},
    {"id": "C", "depth": 2},
    {"id": "D", "depth": 3},
]

let res = nodes_data.map((d, i) => ({...d, x: i * 100 + 50, y: d.depth * 100 }))

console.log(res)

答案 2 :(得分:0)

您还可以使用reduce()获得所需的结果。

演示

const nodes_data =  [
    {"id": "A", "depth": 1},
    {"id": "B", "depth": 2},
    {"id": "C", "depth": 2},
    {"id": "D", "depth": 3},
];

let i = 0;

let result = nodes_data.reduce((r, o) => {
  let x = i + 50,
    y = i + 100;
  i = y;
  return [...r, Object.assign({},o,{x,y})];
}, []);

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

答案 3 :(得分:0)

使用Array.map  简直就是

function presetCoordinates(arr){
    return arr.map(function(data, idx){

        data.x = (idx * 100) + 50; 
        data.y = data.depth * 100; 
        return data;        
    });
}

var nodes_data =  [
    {"id": "A", "depth": 1},
    {"id": "B", "depth": 2},
    {"id": "C", "depth": 2},
    {"id": "D", "depth": 3},
];

let nodes_with_coords = presetCoordinates(nodes_data)
console.log(nodes_with_coords)