How to get correct order of js object? - javascript

I have the question about js obj order:
When I define:
var objJSON = {};
objJSON[31] = '123'; ------------- (1)
objJSON[23] = '456'; ------------- (2)
And alert the object:
alert(JSON.stringify(objJSON, null, 4));
It shows:
"
{
"23":"456",
"31":"123"
}
"
I would like to get the object by the order of inserting:
"
{
"31":"123",
"23":"456"
}
"
How to do so?

The properties of an object don't have a guaranteed ordering. If the key, value and position is important, I would recommend an array of objects instead:
var x = [];
x.push({
key: 23,
value: '123'
});
x.push({
key: 31,
value: '456'
});
JSON.stringify(x); // [{"key":23,"value":"123"},{"key":31,"value":"456"}]

JavaScript objects cannot be counted on to maintain order. You will likely want to use an array instead, which will preserve index order.
Just change {} to [] in your first line.
var objJSON = [];

You're using an object (which can be thought of as a "map" for this purpose), when you need an array. Objects do not guarantee order. What if you happen to add another property later? It will also skew the order. Try using an array/list/vector of objects instead. For example:
var array = [];
array[0] = { 31: '123' };
array[1] = { 23: '456' };

A dictionary is a data structure that does not preserve order by definition.
You will need to sort the dictionary yourself by key or by value.
Check this:
sort a dictionary (or whatever key-value data structure in js) on word_number keys efficiently

try this:
var objList = [];
objList.push({"31" : "123"});
objList.push({"23" : "456"});
alert(JSON.stringify(objList));

You need to put the key-value pairs in an array so you get
{
"array": ["31":"123", "23":"456"]
}

Related

Convert Object to JSON Object

I am using DataTables library and I have hard times in receiving data in a proper format so I am trying to adjust it before DataTable library tries to fetch data into table. I have an ajax call which returns an object of the following format:
data:[ [{ Key: "SomeKey" , Value: "SomeValue" } , { ...} ],[...] ]
And my desired output is: data:[ [{ "SomeKey":"SomeValue" } , { ...} ],[...] ]
I have tried JSON.stringify or eval method , but did not worked , also tried those 2 methods when return type was some sort of string but then it inserts \ before " so It does not convert to json. Any help or good tracks would be appreciated.
This has nothing to do with JSON. :-)
data is apparently an array of arrays of objects, where each object has properties valled Key and Value.
If you want to create a new array of arrays of objects, where the objects have a property named by the Key value whose value is the Value value, you can do that like this:
data = data.map(a => a.map(({Key,Value}) => ({[Key]: Value})));
That uses map on the arrays (both the outer and inner ones) and destructuring to pick out the Key and Value properties from each object in the subarrays, and uses computed property names to set the property name on the new object.
In ES5 and earlier, that would look like this:
data = data.map(function(a) {
return a.map(function(obj) {
var newObj = {};
newObj[obj.Key] = obj.Value;
return newObj;
});
});
You should look into Array.prototype.map (mdn)
let data = [[{Key: "SomeKey", Value: "SomeValue"}]];
let output = data.map(a => a.map(({Key, Value}) => ({[Key]: Value})));
console.log(output);
Note the [Key] syntax. To put it simply, whereas var x = 'key'; y = {x: 3} will assign the object {x: 3}, x = 'key'; y = {[x]: 3} will assign the object {key: 3}.
If you're receiving literally the string "data:[ [{ Key: "SomeKey" , Value: "SomeValue" } , { ...} ],[...] ]", then you may trim the first 5 characters ('data:') and then use JSON.parse.

How to print all keys from an object each on a separate line

I can not figure out how to print each key on a separated line.
The function prints each key of the input on a separate line. That is, it prints all keys of the key-value store separated by new line characters.
I'm able to print all the keys, just not on separate lines like it asks.
function print_keys(x){
console.log(Object.keys(x));
}
Expected
"stand
rip
rating
pollution
fixed
"
But got "stand,rip,rating,pollution,fixed"
Use forEach:
var obj = {
name: "Jack",
age: 300,
leet: true
};
Object.keys(obj).forEach(key => console.log(key));
Alternatively, you could print them all in the one console.log statement using join with a newline \n:
var obj = {
name: "Jack",
age: 300,
leet: true
};
console.log(Object.keys(obj).join("\n"));
Object.keys returns an array, so you should iterate on it. Like this:
function print_keys(x){
var keys = Object.keys(x);
for(i = 0; i < keys.length; i++){
console.log(keys[i]);
}
}
Object.keys(x) will return you an array and print the array through console.log. An array can be iterated through, and each individual item examined for printing. That's likely what you're looking for.
Object.keys returns an array, simply turn the ruslt into string like this;
console.log(Object.keys(x).toString());

How to create dynamically a simple json array?

I know this questions exists like 100 times, but I just can't transfer the solutions to my code, so I hope you can help me. This should be pretty easy but I just don't get it working.
This is just my code with other variable because of reasons:
My Code:
for (var key in array) {
}
The JSON I want:
[{
key: "One",
y: 5
}, {
key: "Two",
y: 2
},];
Pseudo JSON:
[{
key: key,
y: array[key].data
},{
key: key,
y: array[key].data;
},];
You can try this solution:
var data = [];
for (var key in array) {
data.push({
key : key,
y : array[key].data
});
}
console.log(data);
But, what about Pseudo JSON:?
DEMO - See console (chrome) for output
I don't understand what is 'array'. Is it an object or an array?
I think what you want might be this, if 'array' is an array:
var new_arr = [];
your_array.forEach( function(entry) {
new_arr.push({key: entry, y: entry.data}); // you should change it according to your need.
})
return JSON.stringify(new_arr);
Or if 'array' is just an object, you may need this:
var new_arr = [];
for (key in array) {
new_arr.push({key: key, y: array[key].data}); // you should change it according to your need.
}
return JSON.stringify(new_arr);
JSON is just a syntax for expressing objects and arrays independently of a scripting language's syntax.
Apparently you want to convert your array into another structure and have this expressed in JSON. The conversion to JSON is usually performed by the built-in function JSON.stringify.
Assuming your array isn't really an array (which has only numeric indices, usually without gaps), but more an object-like structure, I'd suggest the following code:
var data = []
for (var key in array)
{
data.push({key: key, y: array[key].data});
}
var json = JSON.stringify(data);
//...
If array really was an array you shouldn't use a for-in-loop. Otherwise you should consider renaming it to avoid confusion.
you can use following line to create an array of json
var jsonArr = [];
then you can create json object from following line
var obj = new Object();
put data in json object as following
obj['id'] = 123;
obj['name'] = 'ABC';
then put json object in json array as
jsonArr.push(obj);
you want to add multiple objects in json array then simply create json object and add one by one using push method.
[{"id":"123","name":"ABC"}]

How to delete an object from array by reference (javascript)?

Simple question, but I cannot find a solution.
I have an array of objects.
I also have a reference to an object from this array.
I want to delete the object from the array.
How to do it in Javascript (without comparing object properties)?
PS It is easy to do it in C# (using List collection)
List<SomeObject> list = ........ ;
SomeObject element = ......... ;
list.Remove(element);
You can use indexOf to get the index of the object and splice to remove it from the array:
var arr = [ { name: 0}, { name : 1 } , {name : 2 } ];
var myObj = arr[1];
arr.splice(arr.indexOf(myObj),1);
console.log(arr);
There is no way to do this with arrays directly. You will have to find or roll your own implementation of an collection which supports similar operation.

Adding elements to object

I need to populate a json file, now I have something like this:
{"element":{"id":10,"quantity":1}}
And I need to add another "element". My first step is putting that json in a Object type using cart = JSON.parse, now I need to add the new element.
I supposed I must use cart.push to add another element, I tried this:
var element = {};
element.push({ id: id, quantity: quantity });
cart.push(element);
But I got error "Object has no method push" when I try to do element.push, and I think I'm doing something VERY wrong because I'm not telling the "element" anywhere.
How can I do that?
Edit: sorry to all I had a LOT of confusion in my head.
I thought I can get only object type when taking data from JSON.parse, but I get what I put in the JSON in the first place.
Putting array instead of object solved my problem, I used lots of suggestions got here too, thank you all!
Your element is not an array, however your cart needs to be an array in order to support many element objects. Code example:
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);
If you want cart to be an array of objects in the form { element: { id: 10, quantity: 1} } then perform:
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push({element: element});
JSON.stringify() was mentioned as a concern in the comment:
>> JSON.stringify([{a: 1}, {a: 2}])
"[{"a":1},{"a":2}]"
The line of code below defines element as a plain object.
let element = {}
This type of JavaScript object with {} around it has no push() method. To add new items to an object like this, use this syntax:
element[yourKey] = yourValue
To put it all together, see the example below:
let element = {} // make an empty object
/* --- Add Things To The Object --- */
element['active'] = true // 'active' is the key, and 'true' is the value
console.log(element) // Expected result -> {type: true}
element['state'] = 'slow' // 'state' is the key and 'slow' is the value
console.log(element) // Expected result -> {type: true, state: 'slow'}
On the other hand, if you defined the object as an array (i.e. using [] instead of {}), then you can add new elements using the push() method.
To append to an object use Object.assign
var ElementList ={}
function addElement (ElementList, element) {
let newList = Object.assign(ElementList, element)
return newList
}
console.log(ElementList)
Output:
{"element":{"id":10,"quantity":1},"element":{"id":11,"quantity":2}}
If the cart has to be stored as an object and not array (Although I would recommend storing as an []) you can always change the structure to use the ID as the key:
var element = { quantity: quantity };
cart[id] = element;
This allows you to add multiple items to the cart like so:
cart["1"] = { quantity: 5};
cart["2"] = { quantity: 10};
// Cart is now:
// { "1": { quantity: 5 }, "2": { quantity: 10 } }
Adding new key/pair elements into the original object:
const obj = { a:1, b:2 }
const add = { c:3, d:4, e: ['x','y','z'] }
Object.entries(add).forEach(([key,value]) => { obj[key] = value })
obj new value:
{a: 1, b: 2, c: 3, d: 4, e: ['x', 'y', 'z'] }
I was reading something related to this try if it is useful.
1.Define a push function inside a object.
let obj={push:function push(element){ [].push.call(this,element)}};
Now you can push elements like an array
obj.push(1)
obj.push({a:1})
obj.push([1,2,3])
This will produce this object
obj={
0: 1
1: {a: 1}
2: (3) [1, 2, 3]
length: 3
}
Notice the elements are added with indexes and also see that there is a new length property added to the object.This will be useful to find the length of the object too.This works because of the generic nature of push() function
you should write var element = [];
in javascript {} is an empty object and [] is an empty array.
cart.push({"element":{ id: id, quantity: quantity }});
function addValueInObject(object, key, value) {
var res = {};
var textObject = JSON.stringify(object);
if (textObject === '{}') {
res = JSON.parse('{"' + key + '":"' + value + '"}');
} else {
res = JSON.parse('{' + textObject.substring(1, textObject.length - 1) + ',"' + key + '":"' + value + '"}');
}
return res;
}
this code is worked.
Try this:
var data = [{field:"Data",type:"date"}, {field:"Numero",type:"number"}];
var columns = {};
var index = 0;
$.each(data, function() {
columns[index] = {
field : this.field,
type : this.type
};
index++;
});
console.log(columns);
If anyone comes looking to create a similar JSON, just without using cart as an array, here goes:
I have an array of objects myArr as:
var myArr = [{resourceType:"myRT",
id: 1,
value:"ha"},
{resourceType:"myRT",
id: 2,
value:"he"},
{resourceType:"myRT",
id: 3,
value:"Li"}];
and I will attempt to create a JSON with the following structure:
{
"1":{"resourceType":"myRT","id":"1","value":"ha"},
"2":{"resourceType":"myRT","id":"2","value":"he"},
"3":{"resourceType":"myRT","id":"3","value":"Li"}
}
you can simply do-
var cart = {};
myArr.map(function(myObj){
cart[myObj.id]= myObj;
});
function addValueInObject(value, object, key) {
var addMoreOptions = eval('{"' + key + '":' + value + '}');
if(addMoreOptions != null) {
var textObject = JSON.stringify(object);
textObject = textObject.substring(1,textObject.length-1);
var AddElement = JSON.stringify(addMoreOptions);
object = eval('{' + textObject +','+ AddElement.substring(1,AddElement.length-1) + '}');
}
return object;
}
addValueInObject('sdfasfas', yourObject, 'keyname');
OR:
var obj = {'key':'value'};
obj.key2 = 'value2';
For anyone still looking for a solution, I think that the objects should have been stored in an array like...
var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);
Then when you want to use an element as an object you can do this...
var element = cart.find(function (el) { return el.id === "id_that_we_want";});
Put a variable at "id_that_we_want" and give it the id of the element that we want from our array. An "elemnt" object is returned. Of course we dont have to us id to find the object. We could use any other property to do the find.
My proposition is to use different data structure that proposed already in other answers - it allows you to make push on card.elements and allow to expand card properties:
let card = {
elements: [
{"id":10,"quantity":1}
],
//other card fields like 'owner' or something...
}
card.elements.push({"id":22,"quantity":3})
console.log(card);
push is an method of arrays , so for object you can get the index of last element ,and you can probably do the same job as push for object as below
var lastIndex = Object.keys(element)[Object.keys(element).length-1];
then add object to the new index of element
element[parseInt(lastIndex) +1] = { id: id, quantity: quantity };
if you not design to do loop with in JS e.g. pass to PHP to do loop for you
let decision = {}
decision[code+'#'+row] = event.target.value
this concept may help a bit
This is an old question, anyway today the best practice is by using Object.defineProperty
const object1 = {};
Object.defineProperty(object1, 'property1', {
value: 42,
writable: false
});
object1.property1 = 77;
// throws an error in strict mode
console.log(object1.property1);
// expected output: 42
In case anyone else needs this, I finally found a good way to add objects or arrays of objects:
var myobj = {}
// These two options only work for single-valued keys, not arrays or objects
myobj["a"] = 1
myobj.b = 2
// This one works for everyting:
Object.assign(myobj, {"key": "value"}); // single-value
// Add object
Object.assign(myobj, {"subobj":
{
"c": 3
}
});
// Add array of objects
Object.assign(myobj, {"subarr":
[
{
"d": 4,
},
{
"e": 5
}
]
});
var newObject = {element:{"id":10,"quantity":1}};
console.log(newObject);

Categories