Javascript 使用 Lodash,将数组转换为无键的普通对象
Javascript using Lodash, convert array to plain object, without keys
const arr = [{a:'1',b:'b',c:'c'},{a:'9',b:'b',c:'c'},{a:'3',b:'b',c:'c'}]
const g = _.toPlainObject(arr)
console.log(_.mapValues(g))
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
问题是我如何获得结果中每个对象前面的索引键0,1,2
,并根据每个对象的值获得真正普通的对象。
预期结果:
{
"1": {
"a": "1",
"b": "b",
"c": "c"
},
"9": {
"a": "9",
"b": "b",
"c": "c"
},
"3": {
"a": "3",
"b": "b",
"c": "c"
}
}
这不是有效的数据结构,违反了 javascript 中 objects
的规则。 python 中的对象或字典将始终形成键值对,例如 { key: value }
您可以使用 Object.values()
获取每个键的值。这将 return 一个对象数组,其中包含您可以使用的所有值。但总的来说,你的数据结构不正确。
使用 _.mapKeys()
从对象的值中获取键。
注意:由于值是数字(整数字符串),因此对象属性将按升序显示。
const arr = [{a:'1',b:'b',c:'c'},{a:'9',b:'b',c:'c'},{a:'3',b:'b',c:'c'}]
const result = _.mapKeys(_.toPlainObject(arr), o => o.a)
console.log(result)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
您可以使用 Array.reduce 重新映射对象。不需要图书馆。
如果您不熟悉 reduce,我知道这段代码看起来很神秘。我保证它并不像看起来那么复杂。阅读 reduce 的工作原理,你会没事的。 (而且我不确定我在代码中的解释性注释是否有帮助,或者只是让它更难阅读。)
const arr = [{a:'1',b:'b',c:'c'},{a:'9',b:'b',c:'c'},{a:'3',b:'b',c:'c'}]
const result = arr.reduce(
// called for each item in arr. merges the current item and returns the result.
(acc, {a, ...other}) => ( // pull the 'a' value, collect remaining properties in 'other'
{
...acc, // keep prior iterations
[a]: { a, ...other } // set the value of 'a' as a key, whose value is this iteration's entry
}),
{} // start with an empty object
);
console.log(result);
const arr = [{a:'1',b:'b',c:'c'},{a:'9',b:'b',c:'c'},{a:'3',b:'b',c:'c'}]
const g = _.toPlainObject(arr)
console.log(_.mapValues(g))
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
问题是我如何获得结果中每个对象前面的索引键0,1,2
,并根据每个对象的值获得真正普通的对象。
预期结果:
{
"1": {
"a": "1",
"b": "b",
"c": "c"
},
"9": {
"a": "9",
"b": "b",
"c": "c"
},
"3": {
"a": "3",
"b": "b",
"c": "c"
}
}
这不是有效的数据结构,违反了 javascript 中 objects
的规则。 python 中的对象或字典将始终形成键值对,例如 { key: value }
您可以使用 Object.values()
获取每个键的值。这将 return 一个对象数组,其中包含您可以使用的所有值。但总的来说,你的数据结构不正确。
使用 _.mapKeys()
从对象的值中获取键。
注意:由于值是数字(整数字符串),因此对象属性将按升序显示。
const arr = [{a:'1',b:'b',c:'c'},{a:'9',b:'b',c:'c'},{a:'3',b:'b',c:'c'}]
const result = _.mapKeys(_.toPlainObject(arr), o => o.a)
console.log(result)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
您可以使用 Array.reduce 重新映射对象。不需要图书馆。
如果您不熟悉 reduce,我知道这段代码看起来很神秘。我保证它并不像看起来那么复杂。阅读 reduce 的工作原理,你会没事的。 (而且我不确定我在代码中的解释性注释是否有帮助,或者只是让它更难阅读。)
const arr = [{a:'1',b:'b',c:'c'},{a:'9',b:'b',c:'c'},{a:'3',b:'b',c:'c'}]
const result = arr.reduce(
// called for each item in arr. merges the current item and returns the result.
(acc, {a, ...other}) => ( // pull the 'a' value, collect remaining properties in 'other'
{
...acc, // keep prior iterations
[a]: { a, ...other } // set the value of 'a' as a key, whose value is this iteration's entry
}),
{} // start with an empty object
);
console.log(result);