Trying to sort object turns into array object [duplicate] - javascript

This question already has answers here:
Sort JavaScript object by key
(37 answers)
Closed 4 years ago.
This how the default api returns. I want to sort them with basis of min_conversion_count properties.
After sorting the structure changes which is affecting my code. How is it possible to sort them with the property and remain the same format.
Code to sort
var rewarddata = res1.response.reward_list;
// console.log(rewarddata);
sortable_data = [];
console.log(rewarddata);
for (var idx in rewarddata)
{
sortable_data.push([idx,rewarddata[idx]]);
sortable_data.sort(function(a, b) {
return a[1].min_conversion_count - b[1].min_conversion_count;
});
console.log(sortable_data);
}
After sorting it changes like this.

You started out with an object, and you put it into an array in order to sort it; once your array is sorted, you have to turn it back into an object.
const sortedObj = sortable_data.reduce((accum, [key, value]) => {
accum[key] = value;
return accum;
}, {});
Note that property ordering is generally not something to rely on. It would be better to save an array of the sorted keys only, and then use that array instead.

Related

Update one object of an array using spread operator not working [duplicate]

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 8 months ago.
I want to update one object from an array. This is my current working code which is updating the object inside the array
var equipment = this.equipments.find((e) => e.id === this.currentItem.id);
// this property is getting updated successfully in the array
equipment.countryId = this.currentItem.countryId;
But I have many properties in that object so I tried to use spread operator to fully copy the object to the existing object like this
var equipment = this.equipments.find((e) => e.id === this.currentItem.id);
equipment = { ...equipment, ...this.currentItem };
But this does not work. It does not update the object in the array.
Could be because the spread operator totally creates a new object and does not update the existing object?
Is there a way if not spread operator to update all the properties of the object with the new values without needing to explicitly write it for all properties?
Could be because the spread operator totally creates a new object and does not update the existing object?
Yes, you need to return a new array and replace one element, it can be done using array.map:
this.equipments = this.equipments.map(equipment => {
if(equipment.id === this.currentItem.id){
return { ...equipment, ...this.currentItem };
}
return equipment;
});

convert array(2) that has sorted object to object [duplicate]

This question already has answers here:
Does JavaScript guarantee object property order?
(13 answers)
Does ES6 introduce a well-defined order of enumeration for object properties?
(3 answers)
Closed 1 year ago.
I'm trying to sort an object from db
MyOjbect : {
key: {
val1:"value",
val2:"",
val3:time,
val4:...
...}
}
and I sorted the object by val3
const sorted = Object.entries(MyObject)
.sort((x,y) => {x[1].val3 - y[1].val3} );
and got an array type.
0:(2) ["key" , {val1:...val2:...}]
1:(2) ["key" , {val1:...val2:...}]
...
I tried reduce() to make it back to the object type, but it changes to be in unsorted order
How can I keep the order sorted and change the type to the object?
You can't. An object doesn't keep the sort order as an Array does it. If you want to have the keys sorted you need to use an Array.

Javascript object traversal in wrong way [duplicate]

This question already has answers here:
How to keep an Javascript object/array ordered while also maintaining key lookups?
(2 answers)
Closed 7 years ago.
I have a json object in occupancy_list as follows :
I am traversing the object as follows :
for(var prop in occupancy_list)
{
console.log(prop);
}
I am getting values in reverse order. Like at first Room 2 then Room 1. How can I fix it ?
Object properties are unsorted and could always be random. If you need order - get the keys, and iterate them that way:
Object.keys(occupancy_list).sort(function(a, b) {
//sort logic
}).forEach(key) {
//logic on each key
});

Sorting objects inside an array [duplicate]

This question already has answers here:
Sort array of objects by string property value
(57 answers)
Closed 8 years ago.
I have an array of objects, and i am basically breaking my head on sorting it,my array is something like dis :
var myArray = [{1:3},{3:19},{5:53},{6:26},{e:53},{c:107},{B: 2},{f: 5}];
But i have to sort this in such a way that my final output is something like this:
myArray = [{c:107},{5:53},{e:53},{6:26},{3:19},{f: 5},{1:3},{B: 2}];
i.e.; based on the value in each object of array element, the array should sorted in descending order.
Thank you in advance.
You can simply use a comparator function in Array.prototype.sort like this
console.log(myArray.sort(function(first, second) {
return second[Object.keys(second)[0]] - first[Object.keys(first)[0]];
}));
Since the key will be different in every object, we get the actual list of keys and taking only the first item in it.

How to sort object elements in javascript? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sorting a JavaScript object
Sort JavaScript object by key
I have array:
var arr = {}
arr[2323] = 1
arr[123] = 1
...
arr[n+232323] = 1
How to get all element of aobject sorted by key ( number order ? )
for ( key in arr ) {
alert(typeof(key))
}
return string type.
This is not an assosiative array, this is an object. There are no associative arrays in javascript.
Additionally, objects are not ordered. The order of keys in an object is meaningless.
Assuming there's some reason you don't use an Array in the first place, you can get an Array of the enumerable object properties, and sort that Array...
var sorted = Object.keys(my_obj)
.sort(function(a,b) {
return a - b;
});
This assumes the keys are numeric.
Then you can iterate the Array, and use each key to get the value from my_obj...
sorted.forEach(function(key) {
console.log(my_obj[key]);
});
Short answer: You can't.
Long answer: Associative Arrays in JavaScript are really JavaScript objects. When you add a new element, you're really adding a new member to the object. While most browsers will enumerate those members in the order they were added, the standard states that the order is undefined. You can't sort something that is undefined.
JavaScript objects (maps/dictionaries/associative arrays) have no order, you can't sort them. You will need to convert it to an array first. As you only need the keys of your object in your loop, the Object.keys() function (potentionally needs a shim for older browsers) is destined for the task:
var obj = {...};
var keys = Object.keys(obj).sort(function(a,b){return a-b;}); // numerically sorted
for (var i=0; i<keys.length; i++) {
alert(keys[i]);
// access the values by obj[keys[i]]
}

Categories