How do I add one single value to a JSON array? - javascript

I am kind of new to the world of interface, and i found JSON is amazing, so simple and easy to use.
But using JS to handle it is pain !, there is no simple and direct way to push a value, check if it exists, search, .... nothing !
and i cannot simply add a one single value to the json array, i have this :
loadedRecords = {}
i want to do this :
loadedRecords.push('654654')
loadedRecords.push('11')
loadedRecords.push('3333')
Why this is so hard ???!!!

Because that's an object, not an array.
You want this:
var = loadedRecords = []
loadedRecords.push('1234');
Now to your points about JSON in JS:
there is no simple and direct way to push a value
JSON is a data exchange format, if you are changing the data, then you will be dealing with native JS objects and arrays. And native JS objects have all kinds of ways to push values and manipulate themeselves.
check if it exists
This is easy. if (data.someKey) { doStuff() } will check for existence of a key.
search
Again JSON decodes to arrays and objects, so you can walk the tree and find things like you could with any data structure.
nothing
Everything. JSON just translates into native data structures for whatever language you are using. At the end of the day you have objects (or hashes/disctionaries), and arrays which hold numbers strings and booleans. This simplicity is why JSON is awesome. The "features" you seek are not part of JSON. They are part of the language you are using to parse JSON.

Well .push is an array function.
You can add an array to ur object if you want:
loadedRecords = { recs: [] };
loadedRecords.recs.push('654654');
loadedRecords.recs.push('11');
loadedRecords.recs.push('3333');
Which will result in:
loadedRecords = { recs: ['654654', '11', '3333'] };

{} is not an array is an object literal, use loadedRecords = []; instead.

If you want to push to an array, you need to create an array, not an object. Try:
loadedRecords = [] //note... square brackets
loadedRecords.push('654654')
loadedRecords.push('11')
loadedRecords.push('3333')

You can only push things on to an array, not a JSON object. Arrays are enclosed in square brackets:
var test = ['i','am','an','array'];
What you want to do is add new items to the object using setters:
var test = { };
test.sample = 'asdf';
test.value = 1245;
Now if you use a tool like FireBug to inspect this object, you can see it looks like:
test {
sample = 'asdf,
value = 1245
}

Simple way to push variable in JS for JSON format
var city="Mangalore";
var username="somename"
var dataVar = {"user": 0,
"location": {
"state": "Karnataka",
"country": "India",
},
}
if (city) {
dataVar['location']['city'] = city;
}
if (username) {
dataVar['username'] = username;
}

Whats wrong with:
var loadedRecords = [ '654654', '11', '333' ];

Related

How to add an object to JSON (nodeJS)

Yes I already know about
json.newvalue = 'newvalue'
But I'm not looking for that...
I have an empty JSON
plugins = {};
Now I need to add 5 items to it for example:
{"name":"test"}
{"name":"test2"}
I am looking for something like this: plugins.add({"name":"test"})
First, json is a string representation of an object, what you have in your code is an object. However, it seems that you don't want a JavaScript object, but an array.
var plugins = [];
plugins.push({"name":"test"});
plugins.push({"name":"test2"});
plugins will now be
[
{"name", "test"},
{"name", "test2"}
]

C# Dictionary equivalent in JavaScript

Is there exist any kind of c# dictionary in JavaScript. I've got an app in angularjs that requests data from an MVC Web Api and once it gets, it makes some changes to it. So the data is an array of objects, which is stored in the MVC Web Api as a Dictionary of objects, but I convert it to list before passing it throug network.
If I convert the Dictionary directly to JSon I get something like:
array = [ {Id:"1", {Id:"1", Name:"Kevin Shields"}},
{Id:"2", {Id:"2", Name:"Natasha Romanoff"}}
];
Well the objects are a little more complex, but you've got now an idea. The problem is that this format is even harder to operate with (I've got alphabetical keys or ids). So is there any equivalent to a dictionary? It's quite simple to do thing like:
Object o = dictionary["1"];
So that's it, thank in advance.
You have two options really, although both essentially do the same thing, it may be worth reading a bit more here, which talks about associative arrays (dictionaries), if you wish to tailor the solution:
var dictionary = new Array();
dictionary['key'] = 'value'
Alternatively:
var dict = [];
dict.push({
key: 'key',
value: 'value'
});
Update
Since ES2015 you can use Map():
const dict = new Map();
dict.set('{propertyName}', {propertyValue});
I know this question is a bit older, but in ES2015 there is a new data structure called map that is much more similar to a dictionary that you would use in C#. So now you don't have to fake one as an object, or as an array.
The MDN covers it pretty well. ES2015 Map
Yes, it's called an object. Object have keys and values just like C# dictonaries. Keys are always strings.
In your case the object would look like this:
{
"1": {
"Id": 1,
"Name":" Kevin Shields"
},
"2": {
"Id": 2,
"Name": "Natasha Romanoff"
}
}
The default ASP.net serializer produces ugly JSON. A better alternative would be Json.NET.
My Example:
var dict = new Array();
// add a key named id with value 111
dict.id = 111;
//change value of id
dict.id = "blablabla";
//another way
// add a key named name with value "myName"
dict["name"] = "myName";
//and delete
delete dict.id;
delete dict["name"]
//another way
dict = {
id: 111,
"name": "myName"
};
//And also another way create associate array
var myMap = { key: [ value1, value2 ] };

Every character in an array being recognized with ".hasOwnProperty(i)" in javascript as true with Google Apps Script

This is the array:
{"C8_235550":
{"listing":"aut,C8_235550_220144650654"},
"C8_231252":
{"listing":"aut,C8_231252_220144650654"}}
It was fetched with a GET request from a Firebase database using Google Apps Script.
var optList = {"method" : "get"};
var rsltList = UrlFetchApp.fetch("https://dbName.firebaseio.com/KeyName/.json", optList );
var varUrList = rsltList.getContentText();
Notice the .getContentText() method.
I'm assuming that the array is now just a string of characters? I don't know.
When I loop over the returned data, every single character is getting pushed, and the JavaScript code will not find key/value pairs.
This is the FOR LOOP:
dataObj = The Array Shown At Top of Post;
var val = dataObj;
var out = [];
var someObject = val[0];
for (var i in someObject) {
if (someObject.hasOwnProperty(i)) {
out.push(someObject[i]);
};
};
The output from the for loop looks like this:
{,",C,8,_,2,3,5,5,5,0,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,5,5,5,0,_,2,2,0,1,4,4,6,5,0,6,5,4,",},,,",C,8,_,2,3,1,2,5,2,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,1,2,5,2,_,2,2,0,1,4,4,6,5,0,6,5,4,",},}
I'm wondering if the array got converted to a string, and is no longer recognized as an array, but just a string of characters. But I don't know enough about this to know what is going on. How do I get the value out for the key named listing?
Is this now just a string rather than an array? Do I need to convert it back to something else? JSON? I've tried using different JavaScript array methods on the array, and nothing seems to return what it should if the data was an array.
here is a way to get the elements out of your json string
as stated in the other answers, you should make it an obect again and get its keys and values.
function demo(){
var string='{"C8_235550":{"listing":"aut,C8_235550_220144650654"},"C8_231252":{"listing":"aut,C8_231252_220144650654"}}';
var ob = JSON.parse(string);
for(var propertyName in ob) {
Logger.log('first level key = '+propertyName);
Logger.log('fisrt level values = '+JSON.stringify(ob[propertyName]));
for(var subPropertyName in ob[propertyName]){
Logger.log('second level values = '+ob[propertyName][subPropertyName]);
}
}
}
What you have is an object, not an array. What you need to do is, use the
Object.keys()
method and obtain a list of keys which is the field names in that object. Then you could use a simple for loop to iterate over the keys and do whatever you need to do.

Convert array of objects to object

In my node REST application I have a function that queries a database for several records and returns an array of objects.
Since I want it to return a JSON object, I need a way to convert the array of objects to a single object with all the records inside.
Unfortunately I can't find an example on the internet about doing something like this.
Any help would be appreciated.
Why would you want to do that ? Its totally fine to JSON stringify an Array of items, you'll get a structure like
"[{},{},{},...]"
that is probably even an advantage, because you keep the order of items guaranteed.
See the object function of underscore.js.
Lets assume you have an array of objects with the form:
log {
name: "foo",
log: "bar"
}
Your could do:
var logs,//Array of logs
logObj = {}
for(i=0, i<logs.Length i++) {
logObj[logs[i].Name] = logs[i].log;
}
After the loop logObj should be:
logObj {
foo: bar,
nextName: cool comment,
etc.
}

Add value to json root dynamically

Well, I'm so confused. I have made a json element like this:
var world = {"county": []};
world.county.push({name: "America", flag: "yes", countries: []});
world.county[0].countries.push({name: "Costa Rica", capital: "San Jose"});
This leads me to think two things:
I'm mixing arrays with json objects. How can I avoid using arrays in this scenario?
How can I add elements to the json root dynamically?
Regarding question 2, I'm facing issues because I don't know how to add elements to the root, let's say that I have tried this, but it doesn't work:
var index = 0;
var word = {};
world.index.push({name: WA});
So, by this way I could add elements iterating some array created previously.
First, let's get this out of the way: it's only JSON if it's a string representing a JavaScript object. What you have there is an object literal.
Now, as for your question, you can add elements to an object simply by using:
object.newProperty = value;
As for your wanting to avoid arrays, just use arrays. They are the correct type of object to use, and you shouldn't use anything else for that task.
Start with Kolink's answer. Then, for what you are doing here:
var index = 0;
var world = {};
world.index.push({name: "WA"});
It looks like you are trying to add a property to world with the index 0. Given you are then trying to use .push() it would seem you want that property to be an array, in which case you would do that like this:
world[index] = [];
world[index].push({name: "WA"});
Given that world started as an empty object that would create this structure:
{ "0" : [ {name:"WA"} ] }
In a general sense, to access an object property where the property is in a variable you use the [] array-style syntax. So:
world["somePropName"]
// does the same thing as
world.somePropName
// so with a variable:
var x = "somePropName";
world[x]

Categories

Resources