JQuery string to Object Array - javascript

I call the function tabulator() with these params.
$("#tableObj").tabulator("addRow", {id:1, Name:"John", Age:"20"}, true);
I want to pass the Array elements name dynamically,
read from a Json ( '{id:1, Name:"John", Age:"20"}' ).
I mean that column names will change.
Ex : {id:1, Company:"myComp", Address:"myaddress"}
How can I create theses objs from Strings or JSon text?

You could use JSON.parse but be aware that id:1, Name:"John", Age:"20" is NOT valid JSON. The keys must be wrapped in quotes, otherwise it will produce an error.
var str = '{"id":1, "Name":"John", "Age":"20"}';
var obj = JSON.parse(str);
$("#tableObj").tabulator("addRow", obj, true);

Related

Merge Two json array in one in Node Js

I have two json arrays like
var json1 = [{id:1, name: 'xxx' ...}]
var json2 = [{sec:'A', class_name:'xyz' ...}]
I want them merge in to single arrays
var finalObj = [{id:1, name: 'xxx' ...},{id:sec, name: class_name ...},{id:A, name: 'xyz' ...}... ]
If both objects have a property with the same name, then the second object property overwrites the first. The best solution in this case is to use Lodash and its merge() method, which will perform a deeper merge, recursively merging object properties and arrays.
Try this to concatinate two arrays into one.
var finalObj = json1.concat(json2);
I am not sure if I get this right as you have the properties of second array as values in the expected result, but if you want to merge both arrays you could use spread operator:
var finalObj = [...json1, ...json2]

How can i add an json into an index on my json

I'm trying to insert some more data into an json I'm retrieving from an database, I need to insert it into an already existing json index.
I've already tried to do an json[0].push(otherjson), but I don't understand how to do this.
var devices = JSON.parse(result);
//devices = [{ {id:1, name:'device1'},{id:2, name:'device2'} }]
devices[0].push({"data1":{"temp":"100", "humid":"12"}});
var devices = [ {id:1, name:'device1'}, {id:2, name:'device2'} ];
devices[0]['data1'] = [{"temp":"100", "humid":"12"}];
You can push new elements into an array. Note that devices[0] is not an array rather it's an object.
And you can add new key and corresponding values into an object in this way
object.new_key = new_value
hence your code will be devices[0]."data1" = [{"temp":"100", "humid":"12"}];

Output value from Json Array

I'm getting output: [{"ref":"contact.html","score":0.7071067811865475}]
$.getJSON( "index.json", function(content) {
idx = lunr.Index.load(content);
var results = idx.search(variabletosearch);
var final = JSON.stringify(results);
console.log(final);
});
How can I print value of ref? When I console.log(final[0].ref); I get undefined.
EDIT:
JSON.stringify returns a string, not an object. So in this case 'final' is a string that contains the same data that was in the object 'results'
To access the data from an object, you can use result[0].ref, or if you want to use 'final' (although you don't need to), you can do this:
final = JSON.parse(final)
console.log(final[0].ref)
If it's only one object within the array, then the other answers are enough, but since arrays are used to store multiple objects, you can do this as follows:
var arr = [
{"ref": "object1", "score": "1"},
{"ref": "object2", "score": "2"}
]
arr.map(function(object) {
console.log(object.ref)
})
JSFiddle using an alert instead of console.log()
You can also use a loop, but this cleaner.
var a = [{"ref":"contact.html","score":0.7071067811865475}];
a[0].ref;
a[0] is the '0'th (or first) element in the array which is the object literal {"ref":"contact.html","score":0.7071067811865475} from here you can access the object normally using dot notation.
Expanded out a bit:
var a = [{"ref":"contact.html","score":0.7071067811865475}];
var myObject = a[0];
console.log(myObject.ref);
//or with null checking
if (myObject) {
console.log(myObject.ref ? myObject.ref : 'no value');
}
Well, assuming
var myvar = [{"ref":"contact.html","score":0.7071067811865475}];
then:
var myref = myvar[0].ref;

Converting array in object to string

I want the array in an object to be a string. can someone pl help? So im passing an array into an object and Im expecting var expectedResultForObject2 = 'name=bob&age=23&kids=billy&kids=bart&kids=bort'; how can this be attained ?
it("should serialize an object with another object/array in it", function() {
var object2 = {
'name': 'bob',
'age': 24,
'kids': [ 'billy', 'bart', 'bort' ]
};
var expectedResultForObject2 = 'name=bob&age=23&kids=billy&kids=bart&kids=bort';
expect(NUUI.Utils.serializeForQueryString(object2))
.toEqual(expectedResultForObject2);
});
You need serialized result from an object. This can be achieved with jQuery.param()
uri = $.param(object2);
More information on this, you can find in jQuery Manual.
Alternatively, you can make an array object a string simply with .join() method of the array
string = array.join('');
This question is heavily answered in SO
jQuery serialize an object?

Serializing a Javascript object with contained arrays to json?

I have a javascript object that contains a few objects that contain associative arrays. I've been trying to use the json2.js library's stringify function but the output doesn't contain the arrays held in the contained object members.
In my code I start with something like this
obj = {"arr1" : [], "arr2" : [], "arr3" : []};
then I add to it with loops that fill each of the contained arrays
obj[arr*].push[arritem*];
obj[arr*][arritem*] = something;
The arr* and arritem* I put in just to represent the variable I am putting in for the loops.
I try Json.stringify(obj) but the string I get back is
'{"arr1" : [0], "arr2" : [0], "arr3" : [0]}'
I would like to see the ouput as
'{"arr1" : [ "arritem1" : something, "arritem2" : something2], "arr2" : [ "arritem1" : something, "arritem2" : something2], "arr3" : [ "arritem1" : something, "arritem2" : something2]}'
is there a better library for this or is there something I have to do before strinfying?
var obj = {"arr1" : [], "arr2" : [], "arr3" : []};
console.log(JSON.stringify(obj));
Works for me.
Filling the arrays works too.
Update
You imply that you are trying to add elements with non-numeric keys to arrays.
This is not valid. In particular, your desired output is not valid JSON. Arrays have only numeric keys, and they are not included in the JSON itself as they are implicitly, sequentially defined.
Arrays are a special type of Object, which handles numeric indexes for you.
var arr = []; // Create array.
arr.push(1); // There is now one element, with index 0 and value 1.
arr["txt"] = 2; // You tried to create a new element,
// but didn't use .push and gave a non-numeric key.
// This broke your array.
console.log(JSON.stringify(arr));
// Output: [1]
Live demo.
Long story short... don't do this. If you want an "associative array", stick with basic objects:
var obj = {}; // Create object.
obj[0] = 1; // There is now one element, with key "0" and value 1.
obj["txt"] = 2; // There is now a second element, with key "txt" and value 2.
console.log(JSON.stringify(arr));
// Output: {"0":1,"txt":2}
Live demo.
obj.toSource()
this will convert your array to source string.

Categories

Resources