Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting JSON to specific structure

I am generally new to JavaScript programming and front-end in generally so please don't judge me :), today I run into some tough problem and I don't how to solve so any help would be welcome. So here is the problem:

I have some JSON structure like on the JSON Example and it is normal javascript JSON, what I want to do is a format and switch elements in the array to the specific order, for example, let's say I have given this order of elements:

var jsonObject =[{"id":1,"name":"Marco0",
                  "age":0,"startDate":"1990-12-01T00:00:00",
                  "salary":333.2132,"currentRate":0.3}];

var order=["name","age","id","startDate","salary","currentRate"]

And i want to have something like this

var result=["Marco0","0","1","1990-12-01T00:00:00,....]

so the result corresponds to the order that was asked for and to be an array of value. I have also check this and that is the only partial answer.

like image 994
Uncharted Avatar asked Mar 06 '26 22:03

Uncharted


1 Answers

While having an array, you could map the array and map the wanted keys/values for a new array.

var object = [{ id: 1, name: "Marco0", age: 0, startDate: "1990-12-01T00:00:00", salary: 333.2132, currentRate: 0.3 }],
    order = ["name", "age", "id", "startDate", "salary", "currentRate"],
    result = object.map(o => order.map(k => o[k]));
    
console.log(result);
like image 146
Nina Scholz Avatar answered Mar 08 '26 12:03

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!