0

Let's suppose, I have this code:

<div>
    <div>
        <span class="toarray" name="someName-1">someDynamicValue</span>
    </div>
    <div>
        <span class="toarray" name="someName-2">someDynamicValue</span>
    </div>
    <div>
        <span class="toarray" name="someName-3">someDynamicValue</span>
    </div>
</div>

I want to create JSON array from this code:

{
 someName-1: "someDynamicValue", 
 someName-2: "someDynamicValue", 
 someName-3: "someDynamicValue"
}
0

2 Answers 2

1

You can try something like bellow

var data = {};

$('span.toarray').each(function(){
    data[$(this).attr('name')] = $(this).text();
});

console.log(data);

Demo

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

Comments

1

Do this.

Get all the spans with class toarray, loop over them, get each spans text along with attr('name') and push into an object defined above the loop.

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.