我正在寻找做到这一点的最佳方法。我有两个数组(数组 1d 和数组 2d 对象):
let keys = [11, 12];
let values = [
[
{ name: '1', link: '1', history: '1' },
{ name: '2', link: '2', history: '2' }
],
[
{ name: '3', link: '3', history: '3' },
{ name: '4', link: '4', history: '4' }
]
]
我想要的最终结果是一个 map 数组:
[
{ name: '1', link: '1', history: '1' , q : 11},
{ name: '2', link: '2', history: '2' , q : 11},
{ name: '3', link: '3', history: '3' , q : 12},
{ name: '4', link: '4', history: '4' , q : 12}
]
如何使用 lodash 以最有效/最干净的方式做到这一点?谢谢!
This code without lodash :
let arr = [];
let keys = [ 29, 30 ]
let values = [
[
{ name: '1', link: '1', history: '1' },
{ name: '2', link: '2', history: '2' }
],
[
{ name: '3', link: '3', history: '3' },
{ name: '4', link: '4', history: '4' }
]
]
for (let j = 0; j < values.length; j++) {
for (let i = 0; i < values[j].length; i++) {
arr.push({ ...values[j][i], q: keys[j] });
}
}
console.log(arr)
最佳答案
你可以简单地使用_.map
let keys = [11, 12];
let values = [[{"name":"1","link":"1","history":"1"},{"name":"2","link":"2","history":"2"}],[{"name":"3","link":"3","history":"3"},{"name":"4","link":"4","history":"4"}]]
console.log(_.map(values, (v, i) => _.map(v, o => (o.q = keys[i], o))))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.core.js"></script>
或者没有 lodash,语法几乎相同
let keys = [11, 12];
let values = [[{"name":"1","link":"1","history":"1"},{"name":"2","link":"2","history":"2"}],[{"name":"3","link":"3","history":"3"},{"name":"4","link":"4","history":"4"}]]
console.log(values.map((v, i) => v.map(o => (o.q = keys[i], o))))
编辑:我忘记了结果数组必须是一维的。 - lodash 变体需要对结果进行一些 _.flatten - 原生js需要.flat()
最后可以使用 lodash/fp 来获得一些链接样式
let keys = [11, 12];
let values = [[{"name":"1","link":"1","history":"1"},{"name":"2","link":"2","history":"2"}],[{"name":"3","link":"3","history":"3"},{"name":"4","link":"4","history":"4"}]]
console.log(
_.flow(
// we need to use entries to get the index of fp.map
_.entries,
// for each array
_.map(([i, v]) =>
// foreach "history" of the array
_.map(
// merge the key to the current "history"
_.merge({ q: keys[i] }), v)
),
_.flatten
)(values)
)
console.log(
_.flow(
// or its variant
_.map.convert({ cap: false })((v,i) => _.map(_.merge({ q: keys[i] }), v)),
_.flatten
)(values)
)
<script src="https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js"></script>
关于javascript - 如何使用 lodash 将两个数组(数组 1d 和数组 2d 对象)合并为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60580556/