[英]A more efficient way to rearrange Array of Objects?
Hello fellow good devs, 各位资深开发人员大家好,
I want to rearrange this the Array of objects ( array1
) into the same order given in array2
; 我想将此对象数组( array1
)重新排列为array2
给定的顺序; as you may have noticed below, array2 is a simple array which its values are the same key names in array1, so you can say array2 is the 'arranging reference' for array1. 正如您可能在下面注意到的那样,array2是一个简单的数组,其值与array1中的键名相同,因此可以说array2是array1的“排列引用”。
The below code worked for me as expected, but I am not happy with it, so much loops inside loops, i am afraid it may not be efficient. 下面的代码按预期为我工作,但我对此不满意,因为循环中有太多循环,恐怕它可能效率不高。
I thought of using map() but I couldn't figure out how, is there any more efficient way for doing that by using map() or some other method? 我考虑过使用map(),但是我不知道怎么做,是否有更有效的方法通过使用map()或其他方法来做到这一点?
Note: This is a server-side code, so I am not concerned about Browser compatibility. 注意:这是服务器端代码,因此我不关心浏览器的兼容性。
var array1 =
[
{ 'aaa': '1000', 'bbb': '2000' },
{ 'aaa': '3333', 'bbb': '4444' }
]
var array2 = ['bbb', 'aaa'];
var reArrangedArr = [];
array1.forEach(x => {
var obj = {};
for (i = 0; i < array2.length; i++) {
for (key in x) {
console.log(array2[i] + " " + key)
if (array2[i] === key) {
newKey = array2[i];
console.log("equal");
obj[newKey] = x[key]
}
}
}
reArrangedArr.push(obj);
});
console.log(reArrangedArr);
///output: > Array [Object { bbb: "2000", aaa: "1000" }, Object { bbb: "4444", aaa: "3333" }]
You could map the array and map with Object.assign
the keys and their values in the wanted order. 您可以映射数组并使用Object.assign
键按所需顺序Object.assign
键及其值。
With spread syntax ...
, a given iterable, like an array or string, is treated as parameters for the function call. 使用扩展语法...
,给定的可迭代变量(如数组或字符串)被视为函数调用的参数。 Basically it is a syntactic suggar for function.apply(this, array)
. 基本上,这是function.apply(this, array)
的语法建议。
var data = [{ aaa: '1000', bbb: '2000' }, { aaa: '3333', bbb: '4444' }], keys = ['bbb', 'aaa'], reordered = data.map(o => Object.assign(...keys.map(k => ({ [k]: o[k] })))); console.log(reordered);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use Array.reduce()
operation to achieve that: 您可以使用Array.reduce()
操作来实现:
var array1 = [ { 'aaa': '1000', 'bbb': '2000' }, { 'aaa': '3333', 'bbb': '4444' } ]; var array2 = ['bbb', 'aaa']; var reArrangedArr = array1.reduce((acc, obj) => { var tempObj = {}; array2.forEach(item => tempObj[item] = obj[item]); acc.push(tempObj); return acc; }, []); console.log(reArrangedArr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.