How frame Json object dynamically with dynamic key and value strings - javascript

i have a json
i want to add key value pairs (after framing the below format) like
var json = {};
var a = '"key1" : "value1"'; //coming as dynamic
var b = '"key2" : "value2"'; // coming as dynamic
json.push(a); // i know it is wrong.
json.push(b); // i know it is wrong.
console.log(json); // {"key1": "value1", "key2": "value2"} expected
var array = [];
var c = '{"key1": "value1"}';
var d = '{"key2": "value2"}';
array.push(c);
array.push(d);
console.log(array); // ["{"key1": "value1"}", "{"key2": "value2"}"]
like the above i can push objects to array, but how can i push json strings directly to a json object.

Firstly a little clarification; there's no such thing as a 'JSON object'. There is a JSON-formatted string, and there is an object. They are two separate entities.
To add strings to an object, specify the property of the object and set its value. You don't need push() for this as that is used exclusively for arrays. In your case, it should look like this:
var obj = {};
obj.key1 = "value1";
obj.key2 = "value2";
console.log(obj); // = { "key1": "value1", "key2": "value2" }
To set a key dynamically use bracket notation:
var key = 'foo';
obj[key] = 'bar';
console.log(obj); // = { 'foo': 'bar' }
If you need to then convert the object to a JSON string, call JSON.stringify on that object:
var json = JSON.stringify(obj);
Also note that in your second example you end up with an array of strings, not an array of objects. If you want an array of objects you need to remove the quotes around the values you set, like this:
var array = [];
var c = { "key1": "value1" };
var d = { "key2": "value2" };
array.push(c);
array.push(d);
console.log(array); // [{ "key1": "value1" }, { "key2": "value2" }]
Note the difference in the position of the quotes in the objects and the result from the console.

Related

Accesing items with custom keys in object [duplicate]

This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 1 year ago.
I have object like this:
{
"first" : "value1",
"second" : "value2"
}
I want to access both values in for cycle. Order of getting values doesn't mind. Usage is for something like value = value + "something". How to acces values which key names I don't know? Of course I can get keys from helping array like:
var keys = ["first", "second"];
And then get them by index and with them get value1 and value2 from my original array. Is there some better way? For some reason foreach doesn't work either.
Javascript has a for ... in to loop through keys
for (var key in object) {
console.log(object[key])
}
To access both values:
const data = {
"first": "value1",
"second": "value2"
};
// (1) for-loop
for (const [key, value] of Object.entries(data)) {
console.log("for-loop:", key, value);
}
// (2) Array.prototype.forEach
Object.entries(data).forEach(([key, value]) => {
console.log("Array.prototype.forEach:", key, value);
});
If you just want the keys and values separately in an array you can do the following:
var data = {
"first" : "value1",
"second" : "value2"
}
var keys = Object.keys(data)
var values = Object.values(values)
Printing them out individually would give you:
console.log(keys)
Output: ["first", "second"]
console.log(values)
Output: ["value1", "value2"]

Push object into array without key in javascript

I want to push my object without a key in my javascript array. Right now the issue is I psuh my object in the array, but I add extra key 0,1,2 ... I don't want that key. Is there any solution for that? Here I add the code that I implemented.
let newArr = [];
let myId = data['id'];
var key = myId;
var obj = {};
myobj[key] = {
data: "testdata"
};
newArr.push(myobj);
The above code generates output like below. I don't want that 0 key in my array
0: {
260: {
data: 'testdata'
},
}
It's hard to tell what you're wanting, but I expect you don't want to be using an array here at all? You just want a single object that contains all of your key-value pairs?
e.g. something like this:
const data = { id: 1234 };
let myId = data['id'];
var key = myId;
var myobj = {};
myobj[key] = {
data: "testdata"
};
console.log(myobj);
// You can then add more data
myobj[2345] = {
data: "more test data"
};
console.log(myobj);
// Example Property Access
console.log(myobj[2345])
Try this
newArr.push(...myobj);

How can I iterate through a returned JSON string using Javascript?

I have an API endpoint that returns some data in the below format.
{
"key1": "value1",
"key2": "value2",
"key3": "value3",
}
I thought it would be relatively trivial to be able to iterate through each key-value pair in this JSON payload, but I seem to be having errors with it. The code I have below is what I am using to first parse the JSON from string format into a variable, then I want to iterate through each key in the JSON object, retrieve the key and value, and then do something with both of those values.
var dictionary = JSON.parse(data);
for (var key in dictionary) {
var identifier = key;
var identifierValue = dictionary[key];
//do stuff..
I'm not sure whether the for() is valid in this instance, how exactly can I iterate through each key-value pair in the JSON object?
My issue is that I can't seem to access they keys or values held in the dictionary variable. It seems as though the for loop isn't working, which makes me feel like it's invalid for this use case. If this was C# I'd have to do something similar to
for(var key in dictionary.keySet)
{
//do...
}
I'm looking for the equivalent in JS.
The code you posted looks oke, however there are alternative ways to iterate over an object:
Object.keys(jsonObject)
.forEach(function eachKey(key) {
alert(key); // alerts key
alert(jsonObject[key]); // alerts value
});
Your own code seems alright. No idea why it throws an error from the code shown.
The Object.entries() example I commented about goes as follows:
const data_json = '{"key1":"value1","key2":"value2","key3": "value3"}';
const dictionary = JSON.parse( data_json );
Object.entries( dictionary ).forEach(([ key, value ]) => {
console.log( `found key ${ key } with value ${ value }` );
});
It seems you want to know some other ways of doing that. There can be other ways
Object.entries and forEach()
let obj = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
Object.entries(obj).forEach(([key, value]) => {
console.log(key);
console.log(value)
})
Object.keys and forEach()
let obj = {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
Object.keys(obj).forEach(key => {
console.log(key);
console.log(obj[key])
})
If your API data are surrounding by a quotation, then you need to use JSON.parse before run an iterator.
var data = '{"key1": "BMW", "key2": "Volvo", "key3": "Saab", "key4": "Ford"}';
var cars = JSON.parse(data);
Object.keys(cars).forEach(function(key) {
console.log(key + "=" + cars[key]);
});
And if data are plain object, no need to use JSON.parse.
var cars = {"key1": "BMW", "key2": "Volvo", "key3": "Saab", "key4": "Ford"};
Object.keys(cars).forEach(function(key) {
console.log(key + "=" + cars[key]);
});
Your approach is just fine.
You iterate dictionary, it will store the key in var key.
To access the value of this iterated array, you just access the array with the key.
for (var key in dictionary) {
if (dictionary.hasOwnProperty(key)) {
var value = dictionary[key]
console.log(key + '=>' + value);
}
}

JSON.stringify serializes to [[]]

If I create a JavaScript object like:
var lst = [];
var row = [];
row.Col1 = 'val1';
row.Col2 = 'val2';
lst.push(row);
And then convert it to a string:
JSON.stringify(lst);
The result is an object containing an empty object:
[[]]
I would expect it to serialize like:
[[Col1 : 'val1', Col2: 'val2']]
Why do the inner objects properties not serialize?
Code snippet at JSFiddle.
Because row is an array, not an object. Change it to:
var row = {};
This creates an object literal. Your code will then result in an array of objects (containing a single object):
[{"Col1":"val1","Col2":"val2"}]
Update
To see what really happens, you can look at json2.js on GitHub. This is a (heavily reduced) snippet from the str function (called by JSON.stringify):
if (Object.prototype.toString.apply(value) === '[object Array]') {
//...
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
//...
}
//...
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
//...
}
//...
}
//...
Notice that arrays are iterated over with a normal for loop, which only enumerates the array elements. Objects are iterated with a for...in loop, with a hasOwnProperty test to make sure the proeprty actually belongs to this object.
You use your inner array like an object, so make it an object instead of an array.
var lst = [];
var row = {};
row.Col1 = 'val1';
row.Col2 = 'val2';
lst.push(row);
or use it as an array
var lst = [];
var row = {};
row.push( 'val1' );
row.push( 'val2' );
lst.push(row);
You want row to be a dictionary, not a vector. Define it like this:
var row = {};
Since an array is a datatype in JSON, actual instances of Array are stringified differently than other object types.
If a JavaScript Array instance got stringified with its non-numeric keys intact, it couldn't be represented by the [ ... ] JSON array syntax.
For instance, [ "Col1": "val1"] would be invalid, because JSON arrays can't have explicit keys.
{"Col1": "val1"} would be valid - but it's not an array.
And you certainly can't mix'n'match and get { "Col1": "val1", 1, 2, 3 ] or something.
By the way, this works fine:
var lst = [];
var row = {};
row.Col1 = 'val1';
row.Col2 = 'val2';
lst.push(row);
alert(JSON.stringify(lst));​

JavaScript push to array

How do I push new values to the following array?
json = {"cool":"34.33","alsocool":"45454"}
I tried json.push("coolness":"34.33");, but it didn't work.
It's not an array.
var json = {"cool":"34.33","alsocool":"45454"};
json.coolness = 34.33;
or
var json = {"cool":"34.33","alsocool":"45454"};
json['coolness'] = 34.33;
you could do it as an array, but it would be a different syntax (and this is almost certainly not what you want)
var json = [{"cool":"34.33"},{"alsocool":"45454"}];
json.push({"coolness":"34.33"});
Note that this variable name is highly misleading, as there is no JSON here. I would name it something else.
var array = new Array(); // or the shortcut: = []
array.push ( {"cool":"34.33","also cool":"45454"} );
array.push ( {"cool":"34.39","also cool":"45459"} );
Your variable is a javascript object {} not an array [].
You could do:
var o = {}; // or the longer form: = new Object()
o.SomeNewProperty = "something";
o["SomeNewProperty"] = "something";
and
var o = { SomeNewProperty: "something" };
var o2 = { "SomeNewProperty": "something" };
Later, you add those objects to your array: array.push (o, o2);
Also JSON is simply a string representation of a javascript object, thus:
var json = '{"cool":"34.33","alsocool":"45454"}'; // is JSON
var o = JSON.parse(json); // is a javascript object
json = JSON.stringify(o); // is JSON again
That is an object, not an array. So you would do:
var json = { cool: 34.33, alsocool: 45454 };
json.supercool = 3.14159;
console.dir(json);
object["property"] = value;
or
object.property = value;
Object and Array in JavaScript are different in terms of usage. Its best if you understand them:
Object vs Array: JavaScript
Use the push() function to append to an array:
// initialize array
var arr = [
"Hi",
"Hello",
"Bonjour"
];
// append new value to the array
arr.push("Hola");
Now array is
var arr = [
"Hi",
"Hello",
"Bonjour"
"Hola"
];
// append multiple values to the array
arr.push("Salut", "Hey");
Now array is
var arr = [
"Hi",
"Hello",
"Bonjour"
"Hola"
"Salut"
"Hey"
];
// display all values
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Will print:
Hi
Hello
Bonjour
Hola
Salut
Hey
Update
If you want to add the items of one array to another array, you can use Array.concat:
var arr = [
"apple",
"banana",
"cherry"
];
arr = arr.concat([
"dragonfruit",
"elderberry",
"fig"
]);
console.log(arr);
Will print
["apple", "banana", "cherry", "dragonfruit", "elderberry", "fig"]

Categories