编写一个函数来获取客户,只需传递地址 ID 并读取所有客户?参数(地址 ID)



Javascript正如你所看到的,我试图根据地址id获得客户。我很难根据地址获得客户。

var customers = [
{ id: 1, name: "Customer1", email: "customer1@test.com", addresses: [1, 5, 3, 10] },
{ id: 2, name: "Customer2", email: "customer2@test.com", addresses: [2, 8, 10] },
{ id: 3, name: "Customer3", email: "customer3@test.com", addresses: [5, 2] },
{ id: 4, name: "Customer4", email: "customer4@test.com", addresses: [3, 7, 8] },
{ id: 5, name: "Customer5", email: "customer5@test.com", addresses: [4, 6, 9] },
];
var addresses = [
{ id: 1, street: "Riche street", city: "TPT", pin: "232434" },
{ id: 2, street: "Cross street", city: "Vellore", pin: "75646456" },
{ id: 3, street: "Colony", city: "Chennai", pin: "7887878" },
{ id: 4, street: "Annai Nagar", city: "Bangalore", pin: "43545" },
{ id: 5, street: "Main Bazar", city: "Salem", pin: "4567767" },
{ id: 6, street: "Gandhi Nagar", city: "Hosur", pin: "232434" },
{ id: 7, street: "Gandhi Nagar", city: "Pondicherry", pin: "75646456" },
{ id: 8, street: "Colony", city: "Krishanagiri", pin: "7887878" },
{ id: 9, street: "Annai Nagar", city: "Ambur", pin: "43545" },
{ id: 10, street: "Main Bazar", city: "Vaniyambadi", pin: "4567767" },
];
function getCustomers(get_id) {
var arr = [];
for (var i = 0; i < addresses.length; i++) {
if (get_id == addresses[i].id) {
console.log(addresses[i].id);
for (var prop in customers) {
if (customers.hasOwnProperty(prop)) {
if (
prop.addresses.filter((x) => {
x == addresses[i].id;
})
) {
console.log(prop);
}
}
}
}
}
}
getCustomers(10);

我想我错过了什么。。。如果我将10作为参数传递,它将获取属于地址10的客户记录。

输出井为:

{ id: 1, name: "Customer1", email: "customer1@test.com", addresses: [1,5,3,10] },
{ id: 2, name: "Customer2", email: "customer2@test.com", addresses: [2,8,10] },

下面是一个函数,它根据传递的地址ID返回客户列表:

function getCustomers(addressId) {
return customers.filter(customer => {
return customer.addresses.includes(addressId);
});
}

Here You Go

let obj = [
{ id: 1, name: "Customer1", email: "customer1@test.com", addresses: [1,5,3,10] },
{ id: 2, name: "Customer2", email: "customer2@test.com", addresses: [2,8,10] },
{ id: 3, name: "Customer2", email: "customer2@test.com", addresses: [2,8,5] },
{ id: 5, name: "Customer2", email: "customer2@test.com", addresses: [6, 8, 9] },
]
function getCustomers(data, id) { //data will be your object from which to find id
let customers = [];
data.forEach(function(d) {
d.addresses.forEach(function(a) {
if (a == id) {
customers.push(d);
}
});
});
return customers;
}

注意:此函数将以对象数组的形式返回值

最新更新