如何将对象数组转换为单个数组

时间:2018-12-03 18:24:19

标签: javascript

我有这个obj数组

0: "aab9d17c0f0493808331c2da42050e41"
1: "beb9d17c0f0493808331c2da42050e62"
2: "a2b9953c0f0493808331c2da42050e51"
3: "2ab9d17c0f0493808331c2da42050e4a"

将所有这些元素合并到一个数组中的最佳方法是什么?

预期结果

["aab9d17c0f0493808331c2da42050e41","beb9d17c0f0493808331c2da42050e62","a2b9953c0f0493808331c2da42050e51","2ab9d17c0f0493808331c2da42050e4a"]

3 个答案:

答案 0 :(得分:4)

如果要确保保留顺序,可以为对象提供length属性并使用Array.from()

let obj = {
0: "aab9d17c0f0493808331c2da42050e41",
1: "beb9d17c0f0493808331c2da42050e62",
2: "a2b9953c0f0493808331c2da42050e51",
3: "2ab9d17c0f0493808331c2da42050e4a"
}
obj.length = Object.values(obj).length

let arr = Array.from(obj)
console.log(arr)

答案 1 :(得分:0)

尝试一下:

let obj  = 
{0: "aab9d17c0f0493808331c2da42050e41",
1: "beb9d17c0f0493808331c2da42050e62",
2: "a2b9953c0f0493808331c2da42050e51",
3: "2ab9d17c0f0493808331c2da42050e4a"}
console.log(Object.values(obj))

答案 2 :(得分:0)

如果数据顺序很重要,则可以创建一个自定义map-sort-map函数。

const Sorters = {
  sortBy                       : (a, b) => a.localeCompare(b),
  sortByKeyAsString            : (a, b) => a.key.toString().localeCompare(b.key.toString()),
  sortByKeyAsInteger           : (a, b) => a.key - b.key,
  sortByKeyAsIntegerFromString : (a, b) => parseInt(a.key, 10) - parseInt(b.key, 10),
  sortByValueAsString          : (a, b) => a.value.toString().localeCompare(b.value.toString()),
  sortByValueAsInteger         : (a, b) => a.value - b.value
};

function toOrderedArray(obj, sorterFn) {
  return Object.keys(obj)
    .map(key => ({ key : key, value : obj[key] }))
    .sort(sorterFn || Sorters.sortByKeyAsString)
    .map(item => item.value);
}

let data = {
  0: "aab9d17c0f0493808331c2da42050e41",
  1: "beb9d17c0f0493808331c2da42050e62",
  2: "a2b9953c0f0493808331c2da42050e51",
  3: "2ab9d17c0f0493808331c2da42050e4a"
};

console.log(toOrderedArray(data, Sorters.sortByKeyAsInteger));
.as-console-wrapper {
  top: 0;
  max-height: 100% !important;
}