输入
const products = {
100: ['abc', 'xyz', 'mno', 'pqr'],
200: ['mno', 'pqr'],
300: ['abc', 'xyz'],
400: ['abc', 'pqr'],
}
预期
{
abc: [100, 300, 400],
xyz: [100, 300],
mno: [100, 200],
pqr: [100, 400]
}
我的解决方案:
var results = {};
Object.keys(products).forEach(function(id){
console.log(id)
products[id].forEach(function(user){
if(typeof results[user] === 'undefined'){
results[user] = [];
}
results[user].push(id)
})
})
console.log(results)
是否有更好的方法,例如map,reduce..etc?
这里是数组归约
const products=
{ 100: [ 'abc', 'xyz', 'mno', 'pqr']
, 200: [ 'mno', 'pqr']
, 300: [ 'abc', 'xyz']
, 400: [ 'abc', 'pqr']
}
var result= Object.keys(products).reduce((acc, elm)=>
{
for (let ref of products[elm])
{
if (!acc[ref]) acc[ref]= [Number(elm)]
else acc[ref].push(Number(elm))
}
return acc
}
,{})
for (trace in result) console.log(trace, ':', JSON.stringify(result[trace]))
与@ Bergi在他的评论中要求的一样,具有双重减少:
const products=
{ 100: [ 'abc', 'xyz', 'mno', 'pqr']
, 200: [ 'mno', 'pqr']
, 300: [ 'abc', 'xyz']
, 400: [ 'abc', 'pqr']
}
var result = Object.keys(products).reduce((acc, elm) =>
products[elm].reduce((acc, ref) =>
{
if (!acc[ref]) acc[ref]= [Number(elm)]
else acc[ref].push(Number(elm))
return acc
}
, acc)
, {})
for (trace in result) console.log(trace, ':', JSON.stringify(result[trace]))
您的方法很好,我会根据您的要求提供另一个map / reduce示例。
const products = {
100: ['abc', 'xyz', 'mno', 'pqr'],
200: ['mno', 'pqr'],
300: ['abc', 'xyz'],
400: ['abc', 'pqr'],
}
let result = Object.entries(products)
.flatMap(([id,tokens])=>tokens.map(token=>({token,id})))
.reduce((index,{token,id})=>{
if(index[token]) index[token].push(id)
else index[token] = [id]
return index
},{})
console.log(result)