1

I am looking at pushing multiple Json objects into 1 single object.

Currently I am parsing an array from AJAX and it console logs like this

0:{id: "24", user: "Joe", pass: "pass", name: "Joe Bloggs", role: "Technical Support", …}
1:{id: "25", user: "Jim", pass: "pass", name: "Jim Bloggs", role: "Technical Support", …}
2:{id: "26", user: "John", pass: "pass", name: "John Bloggs", role: "Technical Support", …}

I need to run a loop and push all of the id's and user's into a single line, in this exact format

0: {Joe : 24, Jim : 25, John : 26}

How can I do this?

Thanks

1 Answer 1

3

You can reduce the data to a new object:

let a = [{id: "24", user: "Joe", pass: "pass", name: "Joe Bloggs", role: "Technical Support"},
{id: "25", user: "Jim", pass: "pass", name: "Jim Bloggs", role: "Technical Support"},
{id: "26", user: "John", pass: "pass", name: "John Bloggs", role: "Technical Support"}]

let res = a.reduce((a,b) => {
    a[b.user] = b.id;
    return a;
}, {});

console.log(res);

Or if you prefer destructuring

let a = [{id: "24", user: "Joe", pass: "pass", name: "Joe Bloggs", role: "Technical Support"},
{id: "25", user: "Jim", pass: "pass", name: "Jim Bloggs", role: "Technical Support"},
{id: "26", user: "John", pass: "pass", name: "John Bloggs", role: "Technical Support"}]

let res = {};
for (let {id, user} of a) {
    res[user] = id;
}

console.log(res);

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

7 Comments

How do I do this, but pass in a parseJSON result from an AJAX request?
I don't understand the question. Just replace a.reduce with <yourArrayVariable>.reduce @Sam
Sorry, using the destructing method I want to pass in an object I have fetched from an AJAX call. success: function(results) {var result = .parseJSON(results);
Then replace let {id, user} of a with let {id, user} of result... @Sam
This doesn't work, it returns resu;t[symbol.iterator] is not a function
|

Your Answer

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