I have an array with correct order line:
let arr1 = ['name', 'age', 'occupation', 'address']
and I have an another array which is coming from the backend with unsorted format
let arr2 = [{'age': 20, 'address': '', 'occupation': 'student', 'name': 'student name1'}, {'age': 21, 'address': '', 'occupation': 'student', 'name': 'student name2'}, {'age': 22, 'address': '', 'occupation': 'student', 'name': 'student name3'}]
So I need this arr2 objects keys to be sorted the way arr1 keys index positions.
Final output needed:
let arr2Sorted = [{ 'name': 'student name1', 'age': 20, 'occupation': 'student', 'address': ''}, { 'name': 'student name2', 'age': 21, 'occupation': 'student', 'address': ''}, { 'name': 'student name3', 'age': 22, 'occupation': 'student', 'address': ''}]
What I tried:
const arrayMap = arr2.reduce(
(accumulator, currentValue) => ({
...accumulator,
[currentValue]: currentValue,
}),
{},
);
const result = arr1.map((key) => arrayMap[key]);
CodePudding user response:
let arr1 = ['name', 'age', 'occupation', 'address'];
let arr2 = [{'age': 20, 'address': '', 'occupation': 'student', 'name': 'student name1'}, {'age': 21, 'address': '', 'occupation': 'student', 'name': 'student name2'}, {'age': 22, 'address': '', 'occupation': 'student', 'name': 'student name3'}];
let arr3 = arr2.map(i=>Object.fromEntries(arr1.map(p=>[p,i[p]])));
console.log(arr3);
CodePudding user response:
Here I show why it is probably not needed to order the properties, but just use them. I also answer the "How To" in a verbose way.
let arr1 = ['name', 'age', 'occupation', 'address'];
let arr2 = [{
'age': 20,
'address': '',
'occupation': 'student',
'name': 'student name1'
}, {
'age': 21,
'address': '',
'occupation': 'student',
'name': 'student name2'
}, {
'age': 22,
'address': '',
'occupation': 'student',
'name': 'student name3'
}];
// show it is not needed to order props, just use them
const container = document.getElementById("container");
arr2.forEach((el) => {
arr1.forEach((nm) => {
const newtext = document.createTextNode(nm ":" el[nm]);
let dv = document.createElement('div');
dv.appendChild(newtext);
container.appendChild(dv);
});
});
// now show how we an order the props - a number of ways to do this
// this is a super verbose way for clarity
let arrPropsOrdered = [];
arr2.forEach((el, index, array) => {
// console.log("PropName:",arr1[0]);
// console.log("Object:",el);
// console.log("ObjectNameProp:",el[arr1[0]]);
let x = {};
/* manual way
x[arr1[0]] = el[arr1[0]];
x[arr1[1]] = el[arr1[1]];
x[arr1[2]] = el[arr1[2]];
x[arr1[3]] = el[arr1[3]];
*/
// in a loop
arr1.forEach((nm) => {
x[nm] = el[nm];
});
// console.log("X:", x);
arrPropsOrdered.push(x);
// show it pushed in there using the current index
// console.log("PropsByPropName:", arrPropsOrdered[index]);
});
// console.log(arrPropsOrdered);
<div id="container"></div>