Reversing an array of objects in Javascript
console.log()
takes into account whether a mutable object has changed before it has been printed on the screen. And as your process of OUTPUT -> CHANGE -> OUTPUT is almost plesiochronous, both outputs are the same. You have to use a copy of x in order to get the prompt you need.
Try it this way:
// copy x
y = Object.assign({}, x);
console.log(y);
x.reverse();
console.log(x);
Reverse object hierarchy
You could use a recursive function to collect all the values. Then use reduce
to create a nested object from the values:
const initObject = {
value: 5,
next: {
value: 10,
next: {
value: 15,
next: null
}
}
}
const getValues = ({ value, next }) =>
next
? [value, ...getValues(next)]
: [value]
const createObject = values =>
values.reduce((next, value) => ({ value, next }), null)
const output = createObject(getValues(initObject))
console.log(output)
Reverse object in jQuery.each
As it is, you can't in any reliable manner. Because you are enumerating an Object, there is never a guaranteed order.
If you want a guaranteed numeric order, you would need to use an Array, and iterate backwards.
EDIT: This will convert your Object to an Array, and do a reverse iteration.
Note that it will only work if all the properties are numeric.
var data = $.parseJSON($('#sdata').val());
var arr = [];
for( var name in data ) {
arr[name] = data[name];
}
var len = arr.length;
while( len-- ) {
if( arr[len] !== undefined ) {
console.log(len,arr[len]);
}
}
Reversing an Object.entries conversion
Sure, just use .reduce
to assign to a new object:
const input = { key:'val', key2:'val2', key3:'val3' };
const output = Object.entries(input) .filter(([k, v]) => { return true; // some irrelevant conditions here }) .reduce((accum, [k, v]) => { accum[k] = v; return accum; }, {});console.log(output);
How can we get the objects in reverse order from list object?
Would Collections.reverse(list)
work?
Related Topics
Extension Mysqli Is Missing, Phpmyadmin Doesn't Work
How to Get the MAC and the Ip Address of a Connected Client in PHP
How to Remove a Directory That Is Not Empty
How to Submit Multiple PHP Forms While Each Form Has Its Own Submit Button
Telegram Bot Api: How to Send a Photo Using PHP
Convert Image to Base 64 String With Laravel
How to Use a Findby Method With Comparative Criteria
Showing Image Binary Data Using JavaScript
How to Sort a Multidimensional Array in PHP
Getting a File to Download Instead of Opening the Browser
How to Echo Selected Value of Dropdown in PHP
How to Install Imagick/Imagemagick PHP Extension on Windows 7
How to Install Extension for PHP Via Docker-Php-Ext-Install
Laravel - Form Input - Multiple Select for a One to Many Relationship