我要转换:{port:{0: 23, 1: 22},protocol:{0: "http",1:' "https"}}
收件人:[{port: 23, protocol: 'http' },{port: 22, protocol: 'https' }]
我已经编写了手动执行函数。
有没有lodash函数可以做到这一点?或操纵现有功能以获得所需的结果?
答案 0 :(得分:3)
这可能是使用vanillajs的一种方法。
将所有端口和协议映射到两个不同的阵列。
然后组成最终数组,从两个构建的数组中获取值。
这样,您将具有线性复杂度O(n)
。
const a = { port: {0: 23, 1: 22}, protocol: {0: "http",1: "https"} };
const ports = Object.values(a.port);
const protocols = Object.values(a.protocol);
const finalArr = ports.map((port, ind) => ({ port, protocol: protocols[ind] }));
console.log(finalArr);
或者您可以使用zip
的loadash方法:
const a = { port: {0: 23, 1: 22}, protocol: {0: "http",1: "https"} };
const values = Object.values(a).map(e => Object.values(e));
const zipped = _.zip(...values).map(([port, protocol]) => ({ port, protocol }));
console.log(zipped);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
答案 1 :(得分:2)
您可以迭代对象中的条目,并将内部键用作外部数组的键,反之亦然。
var data = { port: { 0: 23, 1: 22 }, protocol: { 0: "http", 1: "https" } },
result = Object.entries(data).reduce((r, [k, o]) => {
Object.entries(o).forEach(([i, v]) => {
r[i] = r[i] || {};
r[i][k] = v;
});
return r;
}, []);
console.log(result);
答案 2 :(得分:1)
没有一个lodash函数可以执行此操作,但是您可以通过_.flow()
创建一个函数来获得所需的结果。
您可以将对象转换为包含标签和值的数组,_.unzip()
要转置,然后使用_.zipObject()
映射到对象:
const obj = { port: {0: 23, 1: 22}, protocol: {0: "http",1: "https"} };
const fn = _.flow([
o => _.map(o, (v, k) => [k, ..._.values(v)]), // convert to an array of label, ...values
_.unzip, // transpose
([labels, ...values]) => _.map(values, v => _.zipObject(labels, v)) // create the ojects
]);
const result = fn(obj);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>