0

i have an array like this coming back response from the server:

[
    [
        "111",
        1
    ],
    [
        "1010",
        4
    ],
    [
        "111",
        5
    ],
    [
        "1010",
        6
    ],
    [
        "1010",
        7
    ]
]

i want to convert it into a JavaScript JSON like this:

[
 {
    "branch":  "111",
    "id":1

 },
 {
    "branch":  "1010",
    "id":4
 },
 {
    "branch":  "111",
     "id":5
 },
 {
    "branch":  "1010",
     "id":6
 },
 {
    "branch":  "1010",
     "id":7
 }
]

If any one can help it will be much appreciable. Bcs i am new to javascript

0

1 Answer 1

7

Explanation:

You can do this with Array#map and destructuring.

Destructuring:

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Array#map:

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

Solution:

const data = [["111",1],["1010",4],["111",5],["1010",6],["1010",7]];

const res = data.map(([branch,id])=>({branch,id}));

res.sort((a,b)=>a.id-b.id);

console.log(res);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.