elize elize - 3 months ago 16
JSON Question

Multi array to javascript json and delete/read them

I have a form like this.

<form id="inform-order">
<input name="example[fname]" />
<input name="example[lname]" />
<input name="example[id]" />
</form>


I want read it by jquery and then convert it to json.

I did this:

<script>
var datastring2 = $("form#inform-order").serializeArray();
var datastringjson = JSON.stringify(datastring2);
</script>


This is for one array.

Now I want merge multi array and convert it to json.
So first for each array,I convereted it to json then merged them.

I did this:

merge_datastringjson = $.extend(datastringjson, new-datastringjson);


Now this my question.

1- My steps are true?

2- How can I remove an array (json object) form list by
example[id]
?

3- How can read
merge_datastringjson
?

NOTE: I convert it to json because I want save it to local storage.

Answer

1- My steps are true?

You don't need JSON.stringify before merge, just use it on merged object (you could use concat() to merge) :

merge_datastringjson  = JSON.stringify( datastring.concat(new_datastring) );

2- How can I remove an array (json object) form list by example[id]?

You could define a small function to do this :

function remove(json, object_name){
    var json = JSON.parse(json);
    var index = -1;

    $.each(json, function(idx, obj) {
        if(obj.name===object_name)
            index = idx;
    });

    if(index!=-1)
        json.splice(index,1);

    return JSON.stringify(json);
}

3- how can read merge_datastringjson?

You could use $.each() :

$.each(JSON.parse(merge_datastringjson), function(idx, obj) {
    alert(obj.name);
});

Hope this helps.

var datastring = $("form#inform-order").serializeArray();
var new_datastring = $("form#inform-order2").serializeArray();

merge_datastringjson  = JSON.stringify( datastring.concat(new_datastring) );

console.log( merge_datastringjson );
console.log( remove(merge_datastringjson, 'example[id]', 12) );

function remove(json, object_name, value){
  var json = JSON.parse(json);
  var index = -1;

  $.each(json, function(idx, obj) {
    if(obj.name===object_name && obj.value==value)
      index = idx;
  });

  if(index!=-1)
    json.splice(index,1);

  return JSON.stringify(json);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="inform-order">
  <input name="example[fname]" />
  <input name="example[lname]" />
  <input name="example[id]" value="12"/>
</form>

<form id="inform-order2">
  <input name="example2[test]" />
</form>

Comments