我有两个对象。一个是单词数组,另一个是第一个数组中的两个单词之间的关系:
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]);
}这给了我一个新的数组,对应于nodes中的索引:
test = [0,1,2,3]那么,现在如何将这些索引分配给links中的属性呢
发布于 2017-08-02 19:43:03
尝试:
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);
发布于 2017-08-02 19:43:16
您可以在第二个数组(而不是第一个)和Object.assign上使用Array#map,以避免原始数据发生突变。
为了降低时间复杂度,可以创建一个Map,它允许在固定时间内获得索引。可以将该映射传递给映射方法的this。通过检查每个属性的匹配项,可以使其成为通用属性,这样算法本身中就没有硬编码的word1或word2:
const nodes = ["apple","cherry","pear","strawberry"]
const 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"}
];
const result = data.map(function(o) {
return Object.assign(...Object.keys(o).map(key => ({
[key]: this.has(o[key]) ? this.get(o[key]) : o[key]
})));
}, new Map(nodes.map( (s,i) => [s,i] )));
console.log(result);.as-console-wrapper { max-height: 100% !important; top: 0; }
发布于 2017-08-02 19:38:22
使用Array#map()创建新数组。获取indexOf(word1)和indexOf(word2)以替换当前值
const nodes = ["apple","cherry","pear","strawberry"];
const 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"}];
const updatedData = data.map((item) => ({
source: nodes.indexOf(item.word1),
target: nodes.indexOf(item.word2),
weight: item.weight
}));
console.log(updatedData);
https://stackoverflow.com/questions/45459747
复制相似问题