0

I would like to take a JavaScript object that is formatted like:

results = {
   names: [
        "id",
        "first_name"
        ],
    values: [
        [
            1234,
            "Fred"
        ],
        [
            4321,
            "Joe"
        ],
        [
            1123,
            "Mary"
        ]
    ]
}

and turn into this:

    results = {
        [id: 1234, name: "Fred"],
        [id: 4321, name: "Joe"],
        [id: 1123, name: "Mary"]
    }

I tried doing something like this, but I can't get the structure correct:

var data = []
for (i=0; i < results['values'].length; i++ ){
    var innerData = []
    for (b=0; b < results['names'].length; b++ ){
        innerData.push([name:results['names'][b], value: results['values'][i][b]])
    }
    data.push(innerData)
}
console.log(data)

2 Answers 2

2

Problem 1:

results = {
    [id: 1234, name: "Fred"],
    [id: 4321, name: "Joe"],
    [id: 1123, name: "Mary"]
}

and

var data = []

and

[name:results['names'][b]…

An array [] consists a set of values in order.

An object {} consists of a set of key:value pairs.

You are using the wrong one each time. Use {} where you have [] and vice versa


Problem 2:

You say you want objects with id and name keys, but you are trying to create name and value keys. Use the property names you actually want.

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

Comments

0

Try this:

var data = [];
for (i in results['values']){
    var innerData = {}
    var value = results['values'][i];
    for (b in value){
        var key = results['names'][b];
        innerData[key] = value[b]; 
    }
    data.push(innerData);
}
console.log(data);

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.