获取数组项附近的对象

时间:2018-07-22 08:22:22

标签: javascript arrays javascript-objects

所以,我有数据。它是对象的数组。

data = [
  {
    "id": "200",
    "price": "5000"
  },
  {
    "id": "137",
    "price": "8000"
  },
  {
    "id": "230",
    "price": "9000"
  },
  {
    "id": "241",
    "price": "9000"
  },
  {
    "id": "78",
    "price": "10000"
  }
]
json=JSON.parse(data);

我制作类似寻呼机的东西。

我的代码应返回原始元素的附近(上一个和下一个)元素。

不允许更改对象的顺序。

我正在尝试做类似的事情

json.indexOf(JSON.parse('{"id":"200","price":"5000"}'))

但它返回-1

json[0]==JSON.parse('{"id":"200","price":"5000"}')返回false,但我认为这些元素是相似的。

您怎么看?

json=JSON.parse('[{"id":"200","price":"5000"},{"id":"137","price":"8000"},{"id":"230","price":"9000"},{"id":"241","price":"9000"},{"id":"78","price":"10000"}]');
console.log(json.indexOf(JSON.parse('{"id":"200","price":"5000"}')));
console.log(json[0]==JSON.parse('{"id":"200","price":"5000"}'));
console.log(json[0]);
console.log(JSON.parse('{"id":"200","price":"5000"}'));

2 个答案:

答案 0 :(得分:1)

您可以采用一个函数,该函数查找所需的id的索引,并在该索引的开头,索引和索引之后的项之间返回项目,并在数组的开头进行调整。

function getParts(id) {
    var index = array.findIndex(o => o.id === id),
        min = Math.max(index - 1, 0);

    if (index !== -1) {
        return array.slice(min, min + (index ? 3 : 2));
    }
}

var array = JSON.parse('[{"id":"200","price":"5000"},{"id":"137","price":"8000"},{"id":"230","price":"9000"},{"id":"241","price":"9000"},{"id":"78","price":"10000"}]');

console.log(getParts('200'));
console.log(getParts('137'));
console.log(getParts('230'));
console.log(getParts('78'));

答案 1 :(得分:1)

尝试一下,我认为它可以工作,因为'id'属性是唯一的

      var words = [{"id":"200","price":"5000"},{"id":"137","price":"8000"},{"id":"230","price":"9000"},{"id":"241","price":"9000"},{"id":"78","price":"10000"}];
        let k;
        let sayYourKeyId = "137";
        const result = words.find((word, index) => {
          if(word.id == sayYourKeyId){
          k = index;
          }
          });
        
        console.log(words[k-1]);
        console.log(words[k]);
        console.log(words[k+1]);