javascript - 将 javascript 对象从一种形式转换为另一种形式
问题描述
输入
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?
解决方案
这里是 Array Reduce
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]))
推荐阅读
- ios - NSAttributedString 添加自定义属性会丢失 html 标签
- python - 使用稀疏矩阵优化大型 numpy 数组乘法
- python - Is it possible to distinguish operators += and + in class function __add__?
- postgresql - Character Varying Array 是否对数组中的每个元素应用精度限制?
- python - 将文件加载到字典时出现奇怪的python错误
- shopify - 是否可以让客户在 Shopify 中使用用户名而不是电子邮件进行签名?
- javascript - 当涉及键值对时,您可以使用 Javascript Array Map 或 Reduce 吗?
- authentication - Splunk - LDAP 集成 - AuthenticationManagerLDAP 找不到匹配的组和 UserManagerPro - LDAP 登录失败/没有映射到 Splunk
- ruby - lambda函数不适用于每个
- python - Pandas 按连续事件分组的第一个和最后一个之间的差异