skip to Main Content

I want to add a value at first number of an object, but its not adding at first number, How can I do this?

  let obj = {'b': 2, 'c': 3, '3': 33, '4': 44};
  const addNewValue = Object.assign({a: 1}, obj);
  console.log(addNewValue);

Output should be as given below:-

{
  "a": 1,
  "3": 33,
  "4": 44,
  "b": 2,
  "c": 3
}

But getting as given below:-

{
  "3": 33,
  "4": 44,
  "a": 1,
  "b": 2,
  "c": 3
}

Thanks for your efforts!

2

Answers


  1. As you can see below you cannot retain the order because you have numeric key mixed into this.

    If the keys started with alphabetics you could since ES6 rely on order if you keep the traversal order

    The code below shows how the order is already wrong as soon as we try to get the keys in any way

    I posted this as dupe, but it was not. It does however explain why your object is not able to keep the order you gave it

    Sort a JavaScript object by key or value; ES6

    let obj = {'b': 2, 'c': 3, '3': 33, '4': 44};
    const entryToAdd = ["a",1];
    
    let entries = Object.entries(obj);
    let orgKeys = Object.keys(obj);
    
    orgKeys.unshift(entryToAdd[0]);
    entries.unshift(entryToAdd);
    
    const addNewValue = orgKeys.reduce((newObj, key) => {
        newObj[key] = obj[key] || (key === entryToAdd[0] ? entryToAdd[1] : undefined);
        return newObj;
    }, {});
    
    console.log(addNewValue); // NOT what you want but that is what you will get regardless
    Login or Signup to reply.
  2. A JS object doesn’t retain property insertion order with numbers, but Map does.

    You could use a proxy to emulate an object-like map:

    const Obj = new Proxy(class Obj{}, {
      apply(_, __, args){
        return new Obj(...args);
      },
      construct(_, args){
        const obj = Reflect.construct(...arguments);
        const map = new Map;
        
        for(const arg of args){
          for(const key in arg){
           map.set(key, arg[key]);
          }
        }
        
        return new Proxy(obj, {
          getOwnPropertyDescriptor(_, prop) {
            return { configurable: true, enumerable: true, value: map.get(prop) };
          },
          ownKeys(){
             return [...map.keys()];
          },
          get(_, prop){
            if(prop === Symbol.iterator){
              return map.keys.bind(map);
            }
            return map.get(prop);
          },
          set(_, prop, value){
            map.set(prop, value);
            return true;
          }
        });
      }
    
    });
    
    const obj = Obj({b: 1, c: 2}, {1: 3, 2: 4});
    
    const obj2 = Object.assign(Obj({a: 1}), obj);
    
    console.log(obj2);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search