javascript - How to shift values through the keys of an array-like object? - Stack Overflow

For an array I can do:array.push(array.shift())var array = [0, 1, 2, 3, 4, 5];array.push(array.shift()

For an array I can do:

array.push(array.shift())

var array = [0, 1, 2, 3, 4, 5];
array.push(array.shift())

console.log(array); // [1, 2, 3, 4, 5, 0]

For an array I can do:

array.push(array.shift())

var array = [0, 1, 2, 3, 4, 5];
array.push(array.shift())

console.log(array); // [1, 2, 3, 4, 5, 0]

How can I do the same for an object?

Input

var object = {0: 'Fiat', 1: 'Audi', 2: 'BMW', 3: 'Citroën'}

How can I move {0: 'Fiat'} to the end of the object

Expected output:

{0: 'Audi', 1: 'BMW', 2: 'Citroën', 3: 'Fiat'}
Share Improve this question edited Sep 6, 2017 at 9:45 Red asked Sep 6, 2017 at 7:54 RedRed 7,35410 gold badges52 silver badges95 bronze badges 8
  • I dont want to sort the JavaScript object by key. – Red Commented Sep 6, 2017 at 8:00
  • The answer is the same, though: "JavaScript objects1 are not ordered. It is meaningless to try to "sort" them". – Lazar Ljubenović Commented Sep 6, 2017 at 8:00
  • You want to sort it, the point is there is no order in an object – Pablo Lozano Commented Sep 6, 2017 at 8:01
  • 2 I've retracted my vote: I think the question should be re-phrased, but I see it as a valid question: How to shift values through the keys of an array-like object? – Pablo Lozano Commented Sep 6, 2017 at 8:33
  • 1 @LazarLjubenović What exactly makes an order? When you literally write an object in a certain order, in the memory it is presented differently. Only what matters is the case, when we're iterating through the object, then we need an "order". In OP's case iterating the object with a regular for loop (not with for..in) gives the correct order despite of the order in the memory. Hence the goal can be achieved by simply renaming the properties. But as you've stated in a ment, an array should have been used from the beginning. – Teemu Commented Sep 6, 2017 at 8:47
 |  Show 3 more ments

7 Answers 7

Reset to default 4

You can use the following way

var object = {0: 'Fiat', 1: 'Audi', 2: 'BMW', 3: 'Citroën'};

var result = Object.keys(object).map(e => object[e]);
//console.log(result);

result.push(result.shift());
//console.log(result);

let ans = Object.assign({}, result);
console.log(ans);

You could convert you object with the given keys as index to an array, apply the shifting and convert back to an object.

var object = { 0: 'Fiat', 1: 'Audi', 4: 'BMW', 5: 'Citroën' },
    array = Object.keys(object).reduce((r, k, i) => (r[i] = object[k], r), []);

array.push(array.shift());

console.log(Object.assign({}, array)); // { 0: "Audi", 1: "BMW", 2: "Citroën", 3: "Fiat" }

A different approach, while respecting the keys.

var object = { 0: 'Fiat', 1: 'Audi', 4: 'BMW', 5: 'Citroën' },
    keys = Object.keys(object);
    result = Object.assign(...keys.map((k, i) => ({ [k]: object[keys[(i + 1) % keys.length]] })));

console.log(result); // { 0: "Audi", 1: "BMW", 4: "Citroën", 5: "Fiat" }

The object's properties does not have any guarantee on the order, in which they may appear, concise there is no concept as order. I think you need to think more and can find another solution, which does not depend on the properties order.

You can convert your object into an array, do the reordering on the array and convert the array back to an object:

function toObject(arr) {
  var rv = {};
  for (var i = 0; i < arr.length; ++i)
    rv[i] = arr[i];
  return rv;
}

function toArray(object) {
  return Object.keys(object).map(function (key) { return object[key]; });
}


var object = {0: 'Fiat', 1: 'Audi', 2: 'BMW', 3: 'Citroën'}
var array = toArray(object);
array.push(array.shift());
object = toObject(array);

console.log(object);

You should not rely on ordering of object's keys in JavaScript. It's not defined by standard. Objects by definition do not have an ordering, so there is no "end" of the object. It simply doesn't make sense to "move" a key of an object anywhere, since there's no ordering.

The data-structure which does have orders are arrays.

Your object is almost array-like, because all of its keys are consecutive numbers, but it's missing a lenght property. With length, you could turn it into an actual array with Array.from(object).

As Suren said, the object does not guarantee the insertion order. I suggest another approach for example:

const o = {0: 'Fiat', 1: 'Audi', 2: 'BMW', 3: 'Citroën'};
const k = Object.keys(o);
k.push(k.shift());
const result = k.map((v, i) => ({[i]: o[v]}))
   .reduce((acum, v) => Object.assign(acum, v), {});

The approach here is to create and index array, apply the logic (push and shift) then re-build the object with map, and then merge them into one object with reduce. I think this could be shorter (just the reduce) but i wanted to split this up to be more clear.

Teaching: Objects are usually based on a Hash table for lookup by key. As a consequence this usually means you do not have order.

myObj[key] => find value by puting hash of key => returns value

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744226795a4564045.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信