JavaScript 如何通过对象的id在对象数组中打印对象

JavaScript 如何通过对象的id在对象数组中打印对象

在本文中,我们将学习如何在JavaScript中通过对象的id在对象数组中打印对象。我们有一个对象数组,在每个对象中都有一个名为id的键,其值是一个数字。我们需要返回满足指定条件的对象。

有多种方法可以在JavaScript中通过对象的id在对象数组中打印对象:

  • 使用Array.filter()方法
  • 使用Array.find()方法
  • 使用JavaScript中的循环
  • 使用Underscore.js的_.find()函数

方法1:使用Array.filter()方法

此方法用于在应用一些条件后从现有数组中创建一个新数组。

示例:

// This is our array of Objects
let data = [
    { id: 1, name: "a" },
    { id: 2, name: "b" },
    { id: 3, name: "c" },
    { id: 4, name: "d" },
    { id: 5, name: "e" },
    { id: 6, name: "f" },
];
 
let idYouWant = 1;
let propertyYouWant = "name";
 
// Using Array.filter( ) method
// we are iterating through each
// items in the array and checking 
// which item's id value is equal
// to the id we want
 
let res = data.filter((item) => {
    return item.id == idYouWant;
});
 
// After using filter method we got
// an array of object. Now take its
// first element and use its 
// 'propertyYouWant' key
let exactRes = res[0][propertyYouWant];
 
// Printing the property we want
console.log(exactRes);

输出

a

方法2:使用Array.find()方法

首先,我们要搜索给定的id在哪个对象中存在,然后我们从该对象中提取name属性。

示例:

// This is our array of Objects
let data = [
    { id: 1, name: "a" },
    { id: 2, name: "b" },
    { id: 3, name: "c" },
    { id: 4, name: "d" },
    { id: 5, name: "e" },
    { id: 6, name: "f" },
];
 
let idYouWant = 2;
let propertyYouWant = "name";
 
// Using Array.find( ) we are searching
// in which object our searching id present
 
let res = data.find((item) => {
    return item.id == idYouWant;
});
 
// Now print the property which you want
// from the object res 
// console.log(res[propertyYouWant])
console.log(res[propertyYouWant]);

输出

b

方法3:使用for循环

使用for循环首先我们遍历数组,查找给定的ID在哪个对象中存在,然后我们打印我们想要的属性。

示例:

// This is our array of objects
let data = [
    { id: 1, name: "a" },
    { id: 2, name: "b" },
    { id: 3, name: "c" },
    { id: 4, name: "d" },
    { id: 5, name: "e" },
    { id: 6, name: "f" },
];
 
let idYouWant = 2;
let propertyYouWant = "name";
 
// Iterating over the array using for 
// loop and searching in which object
// the id present
// After getting the object we print the
// property we wanted from the object
 
for (let i = 0; i < data.length; i++) {
    if (data[i].id == idYouWant) {
        console.log(data[i][propertyYouWant]);
    }
}

输出

b

方法4:使用 Underscore.js 的 _.find() 函数

_.find() 函数 查看列表的每个元素,并返回满足条件的第一个元素的出现。如果列表的任何一个元素不满足条件,则返回 undefined 值。

示例:

// This is our array of Objects
const _ = require('underscore');
let data = [
    { id: 1, name: "a" },
    { id: 2, name: "b" },
    { id: 3, name: "c" },
    { id: 4, name: "d" },
    { id: 5, name: "e" },
    { id: 6, name: "f" },
];
 
let idYouWant = 2;
let propertyYouWant = "name";
 
let obj = _.find(data, function (obj) { 
          return obj.id == idYouWant })
 
// Now print the property which you want
// from the object res 
console.log(obj[propertyYouWant]);

输出:

b  

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程