js 在数组中查找id
时间: 2023-11-30 07:03:16 浏览: 37
如果你想在 JavaScript 中查找数组中是否存在某个特定 id,可以使用 Array.prototype.find() 方法,示例如下:
```javascript
const items = [
{ id: 1, name: 'item1' },
{ id: 2, name: 'item2' },
{ id: 3, name: 'item3' }
];
const idToFind = 2;
const foundItem = items.find(item => item.id === idToFind);
if (foundItem) {
console.log(`Item with id ${idToFind} found:`, foundItem);
} else {
console.log(`Item with id ${idToFind} not found`);
}
```
在上面的示例中,我们定义了一个包含多个对象的数组 `items`,每个对象都包含一个 `id` 和一个 `name` 属性。然后,我们定义了一个要查找的 `id` 值 `idToFind`,使用 `Array.prototype.find()` 方法在数组 `items` 中查找是否存在这个 `id` 值的对象。如果找到,则将其输出到控制台;否则输出未找到的消息。
相关问题
js 在数组中查找id 返回找到查找到的值
如果你想在 JavaScript 中查找数组中是否存在某个特定 id,并且返回查找到的值,可以使用 Array.prototype.find() 方法,示例如下:
```javascript
const items = [
{ id: 1, name: 'item1' },
{ id: 2, name: 'item2' },
{ id: 3, name: 'item3' }
];
const idToFind = 2;
const foundItem = items.find(item => item.id === idToFind);
if (foundItem) {
console.log(`Item with id ${idToFind} found:`, foundItem);
return foundItem;
} else {
console.log(`Item with id ${idToFind} not found`);
return null;
}
```
在上面的示例中,我们定义了一个包含多个对象的数组 `items`,每个对象都包含一个 `id` 和一个 `name` 属性。然后,我们定义了一个要查找的 `id` 值 `idToFind`,使用 `Array.prototype.find()` 方法在数组 `items` 中查找是否存在这个 `id` 值的对象。如果找到,则将其输出到控制台并返回该对象;否则输出未找到的消息并返回 `null`。
js一个多维数组里面查找id
你可以使用递归来查找多维数组中的id。以下是一个例子:
```js
function findId(arr, id) {
for (let i = 0; i < arr.length; i++) {
if (arr[i].id === id) {
return arr[i];
}
if (Array.isArray(arr[i].children)) {
const result = findId(arr[i].children, id);
if (result) {
return result;
}
}
}
return null;
}
```
在这个函数中,我们首先遍历数组中的每个对象。如果当前对象的id与我们要查找的id相同,则返回该对象。如果当前对象具有一个名为“children”的属性,并且该属性是一个数组,则递归调用findId函数,以查找数组中的id。如果在子数组中找到了id,则返回该对象。如果在整个数组中未找到id,则返回null。
以下是一个使用该函数的示例:
```js
const data = [
{
id: 1,
name: 'A',
children: [
{
id: 2,
name: 'B'
},
{
id: 3,
name: 'C'
}
]
},
{
id: 4,
name: 'D',
children: [
{
id: 5,
name: 'E'
},
{
id: 6,
name: 'F'
}
]
}
];
const result = findId(data, 5);
console.log(result); // { id: 5, name: 'E' }
```