繁体   English   中英

在javascript中获取上一个对象项

[英]Get previous object item in javascript

我有一个带有键和数据的对象。 从一个键我想得到上一个项目。

我以前见过类似的话题,但解决方案真的很复杂。

我还添加了一个不起作用的功能,但我希望它能如何工作

简化代码

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);

预期结果

{title:'我的头衔'}

  • ES5甚至ES6都没问题
  • 我更喜欢复杂的解决方案,也许没有循环

对象过去没有订单 ,但实际上他们有,我不会依赖这个订单。

但无论如何,您可以按下一个键/值对进行过滤并获取一个对象。

 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); 

我想有点想这样

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); 

您可以尝试按以获取上一个项目

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;
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM