Get previous object item in javascript

Viewed 1738

I have an object with keys and data. From a key I want to get the previous item.

I've seen similar topics before but the solutions are really complicated.

I also added a function that does not work but how I wish it would work

Simplified code

let obj = {
  slug:        'my-page',
  title:       'My title',
  description: 'My description',
  content:     'My content'
};

let previous = obj.previousItem('description'); // Does not work

console.log(previous);

Expected result

{ title: 'My title' }

  • ES5 or even ES6 is fine
  • I prefer a simple solution to a complicated one, maybe without loops
4 Answers

Object used to be to have no order, but actually they have and I would not rely on this order.

But anyway, you could filter by the next key/value pair and get an object.

let obj = { slug: 'my-page', title: 'My title', description: 'My description', content: 'My content' },
    previous = Object.fromEntries(Object
        .entries(obj)
        .filter((_, i, { [i + 1]: next = [] }) => next[0] === 'description')
    );

console.log(previous);

I think somethink like this

Object.prototype.previousItem = function(propName) {
  const arr = Object.keys(this);
  let indx = arr.indexOf(propName)-1;
  if (indx<0) return null;
  const result = {};
  result[arr[indx]] = this[arr[indx]];
  return result;
}

Object.prototype.previousItem = function(propName) {
  const arr = Object.keys(this);
  let indx = arr.indexOf(propName)-1;
  if (indx<0) return null;
  const result = Object.create(null); // just clear output
  result[arr[indx]] = this[arr[indx]];
  return result;
}

let obj = {
  slug:        'my-page',
  title:       'My title',
  description: 'My description',
  content:     'My content'
};

let previous = obj.previousItem('description'); //  work

console.log(previous);

You can try following to get the previous item

let object = {
    slug: 'my-page',
    title: 'My title',
    description: 'My description',
    content: 'My content'
}
let previous = previousItem(object, 'description');
console.log(previous);


function previousItem(object, str) {
    let lastKey = "";

    for (const key in object) {
        if (object.hasOwnProperty(key)) {
            if (key == str){
                lastKey = lastKey || key;
                let obj = { };
                obj[lastKey] = object[lastKey];
                return obj;
            } else {
                lastKey = key;
            }
        }
    }
}
Related