我有两个对象。一个是单词数组,另一个给出第一个数组中两个单词之间的关系:
nodes = ["apple","cherry","pear","strawberry"]
data = [{word1 : "apple", word2 : "cherry" , weight : "0.1"},
{word1 : "apple", word2 : "strawberry" , weight : "0.2"},
{word1 : "cherry", word2 : "pear" , weight : "0.3"},
{word1 : "cherry", word2 : "strawberry" , weight : "0.4"},
{word1 : "strawberry", word2 : "pear" , weight : "0.5"}]
我想创建一个具有数据结构的新对象,而不是单词,而是它们的索引。就像这样:
links = [{source : "0", target : "1" , value : "0.1"},
{source : "0", target : "3" , value : "0.2"},
{source : "1", target : "2" , value : "0.3"},
{source : "1", target : "3" , value : "0.4"},
{source : "3", target : "2" , value : "0.5"}]
到目前为止我有这个:
for (var i = 0 ; i < nodes.length; i++) {
test[i] = nodes.findIndex(d => d == nodes[i]);
}
这给了我这个新数组,对应于节点
中的索引:
test = [0,1,2,3]
那么我现在该如何将这些索引分配给links
中的属性?
最佳答案
尝试:
var nodes = ["apple","cherry","pear","strawberry"];
var data = [{word1 : "apple", word2 : "cherry" , weight : "0.1"},
{word1 : "apple", word2 : "strawberry" , weight : "0.2"},
{word1 : "cherry", word2 : "pear" , weight : "0.3"},
{word1 : "cherry", word2 : "strawberry" , weight : "0.4"},
{word1 : "strawberry", word2 : "pear" , weight : "0.5"}];
var links = data.map((item) => {
return {
source: nodes.indexOf(item.word1),
target: nodes.indexOf(item.word2),
value: item.weight
};
});
console.log(links);
console.log(data);
关于javascript - 用另一个对象的索引填充一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45459747/