如果我有下面这样的dict:
const d = {"S1": [2, 3, 4], "S2": [5, 6, 7, 8]}
我想创建另一个字典,它可以用相同的键将len或1st元素作为值,比如:
const n = {"S1": 3, "S2": 4} # len of the value array
我尝试使用map
,如下所示:
Object.entries(d).map(([k, v]) => console.log(k, v))
它打印键值对,但我如何使用它来创建一个新字典?
您已经朝着正确的方向迈出了一个良好的开端Object.fromEntries
可用于将键值对数组转换回使用启动的Object.entries
+map
的对象
const d = {"S1": [2, 3, 4], "S2": [5, 6, 7, 8]}
const res = Object.fromEntries(Object.entries(d).map(([k,v]) => [k,v.length]))
console.log(res)
作为一种替代方案,你可以用Object.entries
+reduce
实现同样的效果
const d = {"S1": [2, 3, 4], "S2": [5, 6, 7, 8]}
const res = Object.entries(d).reduce((acc,[k,v]) => ({...acc,[k]:v.length}),{})
console.log(res)
参见内联注释:
function mapLengths(obj) {
// Convert entries back to object:
return Object.fromEntries(
// Convert "d" to entries (tuples) and map:
Object.entries(obj).map(
// Return a tuple with the key and value of the "length" property:
([k, v]) => [k, v?.length],
),
);
}
const d = { "S1": [2, 3, 4], "S2": [5, 6, 7, 8] };
const n = mapLengths(d);
console.log(n); // { S1: 3, S2: 4 }
// If there is a value without a "length" property,
// the optional chaining operator will prevent an invalid access exception
// and just return "undefined":
const d2 = {
"S0": null,
"S1": [2, 3, 4],
"S2": [5, 6, 7, 8],
"S3": {},
"S4": "hello world",
};
const n2 = mapLengths(d2);
console.log(n2); // { S0: undefined, S1: 3, S2: 4, S3: undefined, S4: 11 }