gpt4 book ai didi

javascript - D3 - 如何根据行索引合并 2 个数组

转载 作者:行者123 更新时间:2023-11-30 07:21:22 25 4
gpt4 key购买 nike

我正在使用 D3 进行可视化,需要根据行索引合并 2 个数组:

var links = 
[
{"source":"a0","target":"a0","s_portfolio":"a","t_portfolio":"a","SOURCE_TYPE":"APP","DES_TYPE":"APP"},
{"source":"a1","target":"a2","s_portfolio":"a","t_portfolio":"c","SOURCE_TYPE":"APP","DES_TYPE":"APP"},
{"source":"a1","target":"a2","s_portfolio":"a","t_portfolio":"c","SOURCE_TYPE":"APP","DES_TYPE":"APP"}
];

var files =
[
{"File_Desc":"","DataName":""},
{"File_Desc":"Date","DataName":"Dates.01012016"},
{"File_Desc":"Address","DataName":"Address.01012016"}
];

得到:

var result =
[
{"source":"a0","target":"a0","s_portfolio":"a","t_portfolio":"a","SOURCE_TYPE":"APP","DES_TYPE":"APP","File_Desc":"","DataName":""},
{"source":"a1","target":"a2","s_portfolio":"a","t_portfolio":"c","SOURCE_TYPE":"APP","DES_TYPE":"APP","File_Desc":"Date","DataName":"Dates.01012016"},
{"source":"a1","target":"a2","s_portfolio":"a","t_portfolio":"c","SOURCE_TYPE":"APP","DES_TYPE":"APP","File_Desc":"Address","DataName":"Address.01012016"}
]

最佳答案

如果您可以使用最新模型 JavaScript(又名 ES2015),最短路径是这样的:

var result = links.map((d,i) => Object.assign({}, d, files[i]));

这很短。它也不会修改 linksfiles(如果您希望将它们与 result 分开使用)。

附言

评论表明您担心替代解决方案的运行时间。总的来说,他们都很好,特别是。作为 d3 应用程序中常见的一次性数据设置。但是,如果您有大型数据集或经常运行记录合并,那么您可能需要进行优化。

如果您愿意更新一个现有记录集而不是创建一个新记录集:

links.forEach((d,i) => Object.assign(d, files[i]));

在此之后,links 有更新的记录。这比其他解决方案运行速度快 7-10 倍,大概是因为它没有创建大量新对象。如果您已完成原始的、未合并的 linksfiles 对象,则没有特别理由避免这种“破坏性”或“就地”更新。通常几乎不需要优化一次性设置操作。但如果您想要或需要这样做,这是一个很好的方法。

关于javascript - D3 - 如何根据行索引合并 2 个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41188918/

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