0

for example i have a function like below

        var testName= "";
        testName= $('.test').map(function() {
                    // get text 
                       return $(this).text()
                      // get result as array
                }).get();

            var testResult= {
                name:testName,
            };


        console.log(testResult);

The result i can see from my code is

enter image description here

Which is not something i wanted.

I want to split those data and assign them one by one

"testResult": [
 {
   "name": "test1"
 },
 {
   "name": "Thug life"
 }
]

I tired to use for loop to handle those data but it doesn't help

for(var i; i < testName.length; i++){
                var testName= testName + [{
                    name:testName[i],
                }];
            }
1
  • do you think what you want is a valid ? Commented Sep 27, 2016 at 10:01

1 Answer 1

1

If you want them grouped in the result, return a group in your map.

var testResult = $('.test').map(function() {
    return {name: $(this).text()};
}).get();

console.log(testResult);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="test">test1</div>
<div class="test">test2</div>
<div class="test">test3</div>

Or in your format:

var resultObject = {
    testResult: $('.test').map(function() {
        return {name: $(this).text()};
    }).get()
};

console.log(resultObject);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="test">test1</div>
<div class="test">test2</div>
<div class="test">test3</div>

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

7 Comments

i think OP wants the format "testResult": [ { "name": "test1" }, { "name": "Thug life" } ]
Added that too @guradio
This is a great answer but can i return more than one field ? like "testResult": [ { "name": "test1", "num" : "01" }, { "name": "Thug life" , "num" : "02" } ]
Sure, just add more data into the object, returned in line return {name: $(this).text()};, like return {name: $(this).text(), foo: "bar"};. @anson920520
But i need to get those from a for loop? can i do .map() in .map()?
|

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.