gpt4 book ai didi

Javascript for 循环添加多个项目

转载 作者:行者123 更新时间:2023-12-03 00:42:49 25 4
gpt4 key购买 nike

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

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 和深度开始,我想分别计算 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 是我的“目标”数组。

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

最佳答案

您不包含原始对象:

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)

关于Javascript for 循环添加多个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53368987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com