gpt4 book ai didi

javascript - 获取数组项附近的对象

转载 作者:行者123 更新时间:2023-11-30 14:29:10 26 4
gpt4 key购买 nike

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

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"}'));

最佳答案

您可以采用一个函数来查找所需 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'));

关于javascript - 获取数组项附近的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51463271/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com