Javascript 转换键-值对数组:键表示值,值表示唯一键
我想转换一个用作键值存储的数组数组 每个子数组采用以下形式:['tom'、['hello'、'world']],其中[0]索引'tom'是'key',[1]索引数组是'value' 我希望数组中的所有“值”都是一个新数组的唯一键,数组中的键应该构造新的子数组,其中包含持有相应值的所有先前键 例如:Javascript 转换键-值对数组:键表示值,值表示唯一键,javascript,arrays,key-value,Javascript,Arrays,Key Value,我想转换一个用作键值存储的数组数组 每个子数组采用以下形式:['tom'、['hello'、'world']],其中[0]索引'tom'是'key',[1]索引数组是'value' 我希望数组中的所有“值”都是一个新数组的唯一键,数组中的键应该构造新的子数组,其中包含持有相应值的所有先前键 例如: var myArray = [ ['tom',['hello','world']], ['bob',['world','foo']], ['jim',['foo','bar']
var myArray = [
['tom',['hello','world']],
['bob',['world','foo']],
['jim',['foo','bar']]
];
上述输入应实现以下输出:
var newArray = [
['hello',['tom']],
['world',['tom','bob']],
['foo',['bob','jim']],
['bar',['jim']],
];
我如何才能做到这一点?在讨论“解决方案”之前,我想说明一个事实,即这是一种非常糟糕的存储和描述数据的方法。如果您正在从PHP中寻找类似于关联数组的东西,那么应该学习如何使用 JS中的对象只是唯一键属性->值对的集合 作为对象,您的数据集如下所示:
var before = {
tom: ['hello','world'],
dick: ['world','foo'],
harry: ['foo','bar']
};
var after = {
bar: ["harry"],
foo: ["dick", "harry"],
hello: ["tom"],
world: ["tom", "dick"]
};
下面是一个使用对象的实现。也很天真,但简单多了
之前的变量={
汤姆:[“你好”,“世界”],
迪克:[“世界”,“福”],
哈利:['foo','bar']
};
之后的var={
酒吧:[哈利],
福:[迪克,哈利],
你好:[汤姆],
世界:[汤姆,迪克]
};
函数resobj{
var o={};
对于obj中的var k{
对于变量i=0;iconsole.loginversemyRelation 这里是一个干净的转换函数的实现
/**
* Converts from a one-to-many to many-to-one relationship.
* @param {[array]} pairs [array representing a one-to-many relationship.]
* @return {[array]} [array representing the same data, in a many-to-one relationship]
*/
var oneToManyFlip = function(pairs){
//Recall that current[0] is our 'key'.
//Also recall that 'prev' is the empty object we passed in.
var result = pairs.reduce(function(storage, current, index, array){
current[1].forEach(function(element, index){
if(storage[element] === undefined){ storage[element] = [];}
storage[element].push(current[0]);
});
return storage;
}, {});
return Object.keys(result).map(function(element){
return [element, result[element]];
});
}
我希望它更干净,更容易解释。Map&Reduce在开始时可能会有点棘手
您可以了解更多关于函数式JS的信息。这对于iterables上的这类计算很有用