0

I am terrible at JavaScript but trying to get better. I have a simple autocomplete form that uses a JSON call. The codes looks like this:

        $('#TreasureMakers').ajaxChosen({
            type: 'GET',
            url: '/treasures/find.json',
            dataType: 'json',
            jsonTermKey: 'q',
            placeholder_text_single: 'pick stuff'
                }, function (data) {
                    var results = [];
                    $.each(data, function (i, val) {
                        results.push({ value: val.value, text: val.text });
                    });
            return results;
                });

And find.json returns results like this:

[{
 value: "17854",
 text: "1.00"
 },
 {
 value: "13521",
 text: "1.01"
 },
 ...
}]

I would like to try and rewrite the loop to return the same results, but with JSON source data that looks like this:

results: [{
    Treasure: {
        accnum: "1.00",
        id: "17854"
    }
},
{
    Treasure: {
        accnum: "1.01",
        id: "13521"
}
},
...
]}

I imagine this shouldn't be too hard, but I am not even sure where to start. I tried doing something like this

results.push({ value: val.results[0].Treasure.id text: val.results[0].Treasure.accnum  });

But the Console returns an error and it does not work. Can someone help me with this?

1 Answer 1

1

You can use Array.prototype.map for this:

results.push(val.results.map(function(t){
    return { value: t.Treasure.id, text: t.Treasure.accnum };
});

See the MDN documentation for more information about Array.prototype.map.

Essentially the map function does a transformation: transforming the elements of an array from one thing to another. We're just taking the elements (objects with a property Treasure), and converting them to objects with properties value and text. It's very instructive to set a breakpoint in your code and try various map calls in the console to get a feel for how it works.

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

1 Comment

Thanks, I appreciate the help. My only change was return results[0];

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.