How to add an object to JSON (nodeJS) - javascript

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"}
]

Related

Create Json with specific structure from two different arrays in javascript

I've already tried to find a solution on stack, but I didn't found a possible reply, so I decided to open a topic to ask:
Let's say we have 2 arrays: one containing "keys" and another one containing "values"
Example:
keys = [CO2, Blood, General, AnotherKey, ... ]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[... [
I have to create a Json with a specific structure like:
[{
name: 'CO2',
data: [2,5,4,6]
}, {
name: 'Blood',
data: [4,5,6]
}, {
name: 'General',
data: [1,3,34.5,43.4]
}, {
...
},
}]
I've tried to make some test bymyself, like concatenate strings and then encode it as json, but I don't think is the correct path to follow and a good implementation of it ... I've also take a look on JSON.PARSE, JSON.stringify, but I never arrived at good solution so... I am asking if someone know the correct way to implements it!
EDIT:
In reality, i didn't find a solution since "name" and "data" are no strings but object
Here's one way to get your desired output:
keys = ["CO2", "Blood", "General", "AnotherKey"]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[0] ]
const output = keys.map((x, i) => {
return {"name": x, "data": values[i]}
})
console.log(output)
However, since you're literally constructing key/value pairs, you should consider whether an object might be a better data format to output:
keys = ["CO2", "Blood", "General", "AnotherKey"]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[0] ]
const output = {}
for (let i=0; i<keys.length; i++) {
output[keys[i]] = values[i]
}
console.log(output)
With this data structure you can easily get the data for any keyword (e.g. output.CO2). With your array structure you would need to iterate over the array every time you wanted to find something in it.
(Note: The reason you weren't getting anywhere useful by searching for JSON methods is that nothing in your question has anything to do with JSON; you're just trying to transform some data from one format to another. JSON is a string representation of a data object.)

How to add element to JSON object with Javascript

So say I have a JSON object like this:
{"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI"}
And I can't modify it when it is created. But I want to make it look like this:
{"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI", checked: true}
So how would I do that with javascript?
In the context of JavaScript, there's no such thing as a "JSON Object". What you've got there are JavaScript objects. JSON is a data interchange format that was of course derived from JavaScript syntax, but in JavaScript directly an object is an object. To add a property, just do so:
var object = {"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI"};
object.checked = true;
Now, if what you've really got is a string containing a JSON-serialized object, then the thing to do is deserialize, add the property, and then serialize it again.
With the way your question is currently structured:
> myJson = {"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI"}
Object {name: "asdf", quantity: "3", _id: "v4njTN7V2X10FbRI"}
> myJson.checked = true;
true
> myJson
Object {name: "asdf", quantity: "3", _id: "v4njTN7V2X10FbRI", checked: true}
But I bet you may have to decode and recode first with:
JSON.parse(myJson)
JSON.stringify(myJson)
The entire thing may look like
// get json and decode
myJson = JSON.parse(response);
// add data
myJson.checked = true;
// send new json back
$.post('/someurl/', JSON.stringify(myJson));

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 ] };

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.
}

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

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' ];

Categories

Resources