我有一个对象数组,比如说
[{a:'one',aa:'eleven'},{a:'two',aa:'twelve'},{a:'three',aa:'thirteen'}]
我想将对象转换为数组,就像这样
[['one','eleven'], ['two','twelve'],['three','thirteen']]
作为属性名称应映射到数组中给定的正确索引
这可以使用Lodash或javascript吗?
答案 0 :(得分:5)
如果原始对象中的某些键必须转到数组中的特定插槽,则可以创建插槽编号的键映射。
var data = [{
a: 'one',
aa: 'eleven'
}, {
a: 'two',
aa: 'twelve'
}, {
a: 'three',
aa: 'thirteen'
}];
var keyToSlot = {
a: 0,
aa: 1
};
var result = data.map(function(entry) {
var keys = Object.keys(entry);
return keys.reduce(function(acc, key) {
var slot = keyToSlot[key];
acc[slot] = entry[key];
return acc;
}, []);
});
console.log(result);
答案 1 :(得分:3)
您可以通过抓取每个对象的键,对它们进行排序,然后将它们映射到数组来实现此目的。
const arr = [{a:'one',aa:'eleven'},{a:'two',aa:'twelve'},{a:'three',aa:'thirteen'}]
const res = arr.map(x => Object.keys(x).sort().map(y => x[y]));
console.log(res)

一步一步:
arr.map
遍历每个对象
Object.keys(x).sort()
获取对象的键并按字母顺序对其进行排序。.map(y => x[y])
对上述结果将对象的键转换为相应的值。答案 2 :(得分:2)
以下是使用lodash#map并lodash#unary包裹lodash#map
次迭代的方法。
var result = _.map(data, _.unary(_.map));
var data = [{a:'one',aa:'eleven'},{a:'two',aa:'twelve'},{a:'three',aa:'thirteen'}];
var result = _.map(data, _.unary(_.map));
console.log(result);
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
<强>更新强>
要保留关键订单,您可以将lodash#map
iteratee替换为lodash#at partially,{{3}}应用定义值顺序的keys
。
var keys = ['aa', 'a'];
var result = _.map(data, _.unary(_.partialRight(_.at, keys)));
var data = [{a:'one',aa:'eleven'},{a:'two',aa:'twelve'},{a:'three',aa:'thirteen'}];
var keys = ['aa', 'a'];
var result = _.map(data, _.unary(_.partialRight(_.at, keys)));
console.log(result);
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
上述解决方案的es6替代方案是:
var keys = ['aa', 'a'];
var result = _.map(data, v => _.at(v, keys));
var data = [{a:'one',aa:'eleven'},{a:'two',aa:'twelve'},{a:'three',aa:'thirteen'}];
var keys = ['aa', 'a'];
var result = _.map(data, v => _.at(v, keys));
console.log(result);
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>