将对象数组转换为已排序的数组数组

时间:2017-04-17 17:28:24

标签: javascript arrays typescript lodash

我有一个对象数组,比如说

[{a:'one',aa:'eleven'},{a:'two',aa:'twelve'},{a:'three',aa:'thirteen'}]

我想将对象转换为数组,就像这样

[['one','eleven'], ['two','twelve'],['three','thirteen']]

作为属性名称应映射到数组中给定的正确索引

这可以使用Lodash或javascript吗?

3 个答案:

答案 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#maplodash#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>