Click here to Skip to main content
14,876,231 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi Guys,

I have code like this:

var controlNameAndValues = [
{ controlName: 'txt1', controlValue: 'yellow' },
{ controlName: 'txt2', controlValue: 'blue' },
{ controlName: 'txt3', controlValue: 'red' }

This works perfect but the issue is that now my controlNameAndValues is dynamic. So how can i convert the dynamic controlNameAndValues to work like the above hard coded value. The above controlNameAndValues gives list of objects which has values but the dynamically generated does not have object list like I wanted. Can you please help me out.

What I have tried:

//this is for dynamically generating controlNameAndValue

$("input[type='text']").each(function () {
if ($(this).attr("id") != null) {
var controlName = $(this).attr("id");
var controlValue = $('#' + controlName + '').val();
controlNameAndValues += '{ controlName:' + '\'' + controlName + '\'' + ',controlValue:' + '\'' + controlValue +'\'}';
if(i < $("input[type='text']").length)
controlNameAndValues += ",";
controlNameAndValues += "]";
controlNameAndValues = $.parseJSON(JSON.stringify(controlNameAndValues));
Updated 29-Jun-16 6:21am

Why bother? Instead of creating a JSON string just to parse it back to an object, just build the object instead:
var controlNameAndValues = [];

$("input[type='text'][id]").each(function () {
        controlValue: $(this).val()

// Do something with controlNameAndValues here...
Sergey Alexandrovich Kryukov 29-Jun-16 12:23pm
You are right, a 5.
This is how: JSON.parse() — JavaScript.

Another way is using eval which is not recommended by one good reason: it is unsafe; the string may be not JSON but still evaluate, execute and produce some dangerous side effects.

Richard Deeming 29-Jun-16 12:22pm
Much simpler to avoid the conversion in the first place - see solution 2. :)
Sergey Alexandrovich Kryukov 29-Jun-16 12:27pm
I agree, but I just answered the question on its different level, because it was formulated this way: how to "convert" JSON string. This is still a valid question and the problem unresolved by the inquirer; and my answer is still correct.

At the same time, I fully agree with the idea that many questions should not be answered as formulated, and some more reasonable help should be provided based on what the inquirer really needs, not what he thinks he needs (important difference). I just did not dig into it in this case.


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900