英文:
I want to filter array of objects with a string that should match with a objects property key and should check that key value
问题
I want to check if the person A or B is available on Monday or not.
英文:
I have an array of objects
const workSchedule = [
{
name: 'a',
age: 21,
workDays: {
monday: {isavailable:true}, tuesday:{isavailable:false}, wednesday:{isavailable:true}, thursday:{isavailable:true}, Friday:{isavailable:false}
}
},
{
name: 'b',
age: 22,
workDays: {
monday: {isavailable:false}, tuesday:{isavailable:false}, wednesday:{isavailable:true}, thursday:{isavailable:false}, Friday:{isavailable:false}
}
}
]
and I have a string variable which have a selected Day
const day='Monday'
Now I want to check if the person A or B is available on monday or not?
答案1
得分: 1
以下是您要翻译的内容:
const workSchedule = [
{
name: "a",
age: 21,
workDays: {
monday: { isavailable: true },
tuesday: { isavailable: false },
wednesday: { isavailable: true },
thursday: { isavailable: true },
friday: { isavailable: false },
},
},
{
name: "b",
age: 22,
workDays: {
monday: { isavailable: false },
tuesday: { isavailable: false },
wednesday: { isavailable: true },
thursday: { isavailable: false },
friday: { isavailable: false },
},
},
];
const day = "Monday";
workSchedule.forEach((e) => {
if (e.workDays[day.toLocaleLowerCase()]["isavailable"]) {
console.log(e.name + " is available");
} else {
console.log(e.name + " is not available");
}
});
请注意,我已经将代码部分保持不变,只翻译了注释和字符串部分。
英文:
Try like this,
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const workSchedule = [
{
name: "a",
age: 21,
workDays: {
monday: { isavailable: true },
tuesday: { isavailable: false },
wednesday: { isavailable: true },
thursday: { isavailable: true },
friday: { isavailable: false },
},
},
{
name: "b",
age: 22,
workDays: {
monday: { isavailable: false },
tuesday: { isavailable: false },
wednesday: { isavailable: true },
thursday: { isavailable: false },
friday: { isavailable: false },
},
},
];
const day = "Monday";
workSchedule.forEach((e) => {
if (e.workDays[day.toLocaleLowerCase()]["isavailable"]) {
console.log(e.name + " is available");
} else {
console.log(e.name + " is not available");
}
});
<!-- end snippet -->
答案2
得分: 1
以下是翻译好的部分:
"Here's a better and more reusable snippet Where you retrieve an Array of Objects that contains the available persons only, so you can realize other searches on those persons :"
"这里有一个更好、更可重用的片段,您可以检索包含仅可用人员的对象数组,因此您可以对这些人员进行其他搜索:"
"const workSchedule = [...];"
"const workSchedule = [...];"
"function getAvailablePersons(day){"
"function getAvailablePersons(day){"
"let lowercaseDay = day.toLowerCase();"
"let lowercaseDay = day.toLowerCase();"
"let availablePersons = [];"
"let availablePersons = [];"
"workSchedule.forEach(person => {"
"workSchedule.forEach(person => {"
"if ("
"if ("
"person.workDays &&"
"person.workDays &&"
"person.workDays.hasOwnProperty(lowercaseDay) &&"
"person.workDays.hasOwnProperty(lowercaseDay) &&"
"person.workDays[lowercaseDay].isavailable"
"person.workDays[lowercaseDay].isavailable"
"availablePersons.push(person);"
"availablePersons.push(person);"
"console.log(available persons on ${day}: (${availablePersons.length})
);"
"console.log(available persons on ${day}: (${availablePersons.length})
);"
"availablePersons.forEach(person => {"
"availablePersons.forEach(person => {"
"console.log(- ${person.name}
);"
"console.log(- ${person.name}
);"
"getAvailablePersons('Monday');"
"getAvailablePersons('Monday');"
"getAvailablePersons('Wednesday');"
"getAvailablePersons('Wednesday');"
"const workSchedule = [...];"
"const workSchedule = [...];"
"let availablePersons = [];"
"let availablePersons = [];"
"let day = null;"
"let day = null;"
"function getAvailablePersons(aDay){"
"function getAvailablePersons(aDay){"
"let lowercaseDay = aDay.toLowerCase();"
"let lowercaseDay = aDay.toLowerCase();"
"availablePersons = [];"
"availablePersons = [];"
"workSchedule.forEach(person => {"
"workSchedule.forEach(person => {"
"if ("
"if ("
"person.workDays &&"
"person.workDays &&"
"person.workDays.hasOwnProperty(lowercaseDay) &&"
"person.workDays.hasOwnProperty(lowercaseDay) &&"
"person.workDays[lowercaseDay].isavailable"
"person.workDays[lowercaseDay].isavailable"
"availablePersons.push(person);"
"availablePersons.push(person);"
"return availablePersons;"
"return availablePersons;"
"function listPersons(day){"
"function listPersons(day){"
"day = day.toLowerCase();"
"day = day.toLowerCase();"
"console.log(available persons on ${day}: (${availablePersons.length})
);"
"console.log(available persons on ${day}: (${availablePersons.length})
);"
"availablePersons.forEach(person => {"
"availablePersons.forEach(person => {"
"console.log(- ${person.name}
);"
"console.log(- ${person.name}
);"
"day = 'Monday';"
"day = 'Monday';"
"let personsOnMonday = getAvailablePersons(day);"
"let personsOnMonday = getAvailablePersons(day);"
"console.log(personsOnMonday);"
"console.log(personsOnMonday);"
"listPersons(day);"
"listPersons(day);"
"day = 'Wednesday';"
"day = 'Wednesday';"
"let personsWednesday = getAvailablePersons(day);"
"let personsWednesday = getAvailablePersons(day);"
"console.log(personsWednesday);"
"console.log(personsWednesday);"
"listPersons(day);"
"listPersons(day);"
这是翻译好的部分,没有包含其他内容。
英文:
Here is a way to achieve what you want, but you should try to write the code you have tried so far to reach your goal.
Also, think to be consistent in the variables names in your Object "Friday" the first letter is an upper case.
The first snippet is just to do what you asked, the second one is more reusable to have access to the availablePersons Array out of the function.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const workSchedule = [
{
name: 'a',
age: 21,
workDays: {
monday: { isavailable: true },
tuesday: { isavailable: false },
wednesday: { isavailable: true },
thursday: { isavailable: true },
friday: { isavailable: false }
}
},
{
name: 'b',
age: 22,
workDays: {
monday: { isavailable: false },
tuesday: { isavailable: false },
wednesday: { isavailable: true },
thursday: { isavailable: false },
friday: { isavailable: false }
}
}
];
function getAvailablePersons(day){
let lowercaseDay = day.toLowerCase();
// Array to store available persons
let availablePersons = [];
workSchedule.forEach(person => {
if (
person.workDays &&
person.workDays.hasOwnProperty(lowercaseDay) &&
person.workDays[lowercaseDay].isavailable
) {
availablePersons.push(person);
}
});
// Display available persons
console.log(`available persons on ${day}: (${availablePersons.length})`);
availablePersons.forEach(person => {
console.log(`- ${person.name}`);
});
}
getAvailablePersons('Monday');
getAvailablePersons('Wednesday');
<!-- end snippet -->
Here's a better and more reusable snippet Where you retrieve an Array of Objects that contains the available persons only, so you can realize other searches on those persons :
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const workSchedule = [
{
name: 'a',
age: 21,
workDays: {
monday: { isavailable: true },
tuesday: { isavailable: false },
wednesday: { isavailable: true },
thursday: { isavailable: true },
friday: { isavailable: false }
}
},
{
name: 'b',
age: 22,
workDays: {
monday: { isavailable: false },
tuesday: { isavailable: false },
wednesday: { isavailable: true },
thursday: { isavailable: false },
friday: { isavailable: false }
}
}
];
let availablePersons = [];
let day = null;
function getAvailablePersons(aDay){
let lowercaseDay = aDay.toLowerCase();
// Array to store available persons
availablePersons = [];
workSchedule.forEach(person => {
if (
person.workDays &&
person.workDays.hasOwnProperty(lowercaseDay) &&
person.workDays[lowercaseDay].isavailable
) {
availablePersons.push(person);
}
});
return availablePersons;
}
function listPersons(day){
// Display available persons
day = day.toLowerCase();
console.log(`available persons on ${day}: (${availablePersons.length})`);
availablePersons.forEach(person => {
console.log(`- ${person.name}`);
});
}
day = 'Monday';
let personsOnMonday = getAvailablePersons(day);
console.log(personsOnMonday);
listPersons(day);
day = 'Wednesday';
let personsWednesday = getAvailablePersons(day);
console.log(personsWednesday);
listPersons(day);
<!-- end snippet -->
答案3
得分: 0
以下是您要翻译的代码部分:
const day = 'monday';
const workSchedule = [
{
name: 'a',
age: 21,
workDays: {
monday: { isavailable: true },
tuesday: { isavailable: false },
wednesday: { isavailable: true },
thursday: { isavailable: true },
Friday: { isavailable: false }
}
},
{
name: 'b',
age: 22,
workDays: {
monday: { isavailable: false },
tuesday: { isavailable: false },
wednesday: { isavailable: true },
thursday: { isavailable: false },
Friday: { isavailable: false }
}
}
];
const available = workSchedule.filter(sch => sch.workDays[day.toLowerCase()].isavailable === true);
console.log(available[0]);
console.log(available[0].name);
请注意,我已经将代码部分翻译为中文。
英文:
You can achieve this simply with filter method.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const day = 'monday';
const workSchedule = [
{
name: 'a',
age: 21,
workDays: {
monday: {isavailable:true}, tuesday:{isavailable:false}, wednesday:{isavailable:true}, thursday:{isavailable:true}, Friday:{isavailable:false}
}
},
{
name: 'b',
age: 22,
workDays: {
monday: {isavailable:false}, tuesday:{isavailable:false}, wednesday:{isavailable:true}, thursday:{isavailable:false}, Friday:{isavailable:false}
}
}
];
const available = workSchedule.filter(sch=> sch.workDays[day.toLowerCase()].isavailable === true);
console.log(available[0]);
console.log(available[0].name);
<!-- end snippet -->
答案4
得分: 0
首先,你应该标准化你的输入数据,以使其一致(例如,使用 friday
而不是 Friday
,以及 isAvailable
而不是 isavailable
)。
答案取决于你期望的输出数据类型。这将决定数据查询和操作的方式。
以下是几个示例。
const workSchedule = [{name: "a", age: 21, workDays: {monday: {isAvailable: true}, tuesday: {isAvailable: false}, wednesday: {isAvailable: true}, thursday: {isAvailable: true}, friday: {isAvailable: false}}}, {name: "b", age: 22, workDays: {monday: {isAvailable: false}, tuesday: {isAvailable: false}, wednesday: {isAvailable: true}, thursday: {isAvailable: false}, friday: {isAvailable: false}}}];
const day = 'Monday';
function finder(data, day) {
return data.filter(obj => {
const { name, workDays } = obj;
return workDays[day.toLowerCase()].isAvailable;
}).map(obj => obj.name);
}
const isAvailableOnMonday = finder(workSchedule, day);
console.log(isAvailableOnMonday);
- 在这个示例中,我们只是使用
map
来迭代数据对象,返回一个新的对象数组,描述了特定日期的isAvailable
。
const workSchedule = [{name: "a", age: 21, workDays: {monday: {isAvailable: true}, tuesday: {isAvailable: false}, wednesday: {isAvailable: true}, thursday: {isAvailable: true}, friday: {isAvailable: false}}}, {name: "b", age: 22, workDays: {monday: {isAvailable: false}, tuesday: {isAvailable: false}, wednesday: {isAvailable: true}, thursday: {isAvailable: false}, friday: {isAvailable: false}}}];
const day = 'Monday';
function finder(data, day) {
return data.map(obj => {
const { name, workDays } = obj;
const isAvailable = workDays[day.toLowerCase()].isAvailable;
return { name, day, isAvailable };
});
}
console.log(finder(workSchedule, day));
- 在这个示例中,我们使用
reduce
来创建一个对象,将人名放入特定日期的isAvailable
数组中。
const workSchedule = [{name: "a", age: 21, workDays: {monday: {isAvailable: true}, tuesday: {isAvailable: false}, wednesday: {isAvailable: true}, thursday: {isAvailable: true}, friday: {isAvailable: false}}}, {name: "b", age: 22, workDays: {monday: {isAvailable: false}, tuesday: {isAvailable: false}, wednesday: {isAvailable: true}, thursday: {isAvailable: false}, friday: {isAvailable: false}}}];
const day = 'Monday';
function finder(data, day) {
return data.reduce((acc, obj) => {
const { name, workDays } = obj;
const key = day.toLowerCase();
const { isAvailable } = workDays[key];
acc[key] ??= { isAvailable: [] };
if (isAvailable) acc[key].isAvailable.push(name);
return acc;
}, {});
}
console.log(finder(workSchedule, day));
附加文档:
英文:
First you should standardise your input data to make it consistent (friday
instead of Friday
, for example, and isAvailable
instead of isavailable
).
The answer depends on what kind of data you're expecting as output. This will inform how the data is meant to be queried and manipulated.
Here are a few examples.
- Using
filter
andmap
to create an array of names we can assign to a variable calledisAvailableOnMonday
.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const workSchedule=[{name:"a",age:21,workDays:{monday:{isAvailable:!0},tuesday:{isAvailable:!1},wednesday:{isAvailable:!0},thursday:{isAvailable:!0},friday:{isAvailable:!1}}},{name:"b",age:22,workDays:{monday:{isAvailable:!1},tuesday:{isAvailable:!1},wednesday:{isAvailable:!0},thursday:{isAvailable:!1},friday:{isAvailable:!1}}}];
const day = 'Monday';
// Accepts the data and day as arguments
function finder(data, day) {
// For each object in the data...
return data.filter(obj => {
// Destructure `name` and `workDays` from the object
const { name, workDays } = obj;
// Check to see if that day is available (making sure you
// render the day string to lower case)
return workDays[day.toLowerCase()].isAvailable;
// Finally `map` over the returned array of objects and
// extract their names into a new array
}).map(obj => obj.name);
}
const isAvailableOnMonday = finder(workSchedule, day);
console.log(isAvailableOnMonday);
<!-- end snippet -->
- In this example we're just using
map
to iterate over the data objects to return a new array of objects that describes if a particular dayisAvailable
.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const workSchedule=[{name:"a",age:21,workDays:{monday:{isAvailable:!0},tuesday:{isAvailable:!1},wednesday:{isAvailable:!0},thursday:{isAvailable:!0},friday:{isAvailable:!1}}},{name:"b",age:22,workDays:{monday:{isAvailable:!1},tuesday:{isAvailable:!1},wednesday:{isAvailable:!0},thursday:{isAvailable:!1},friday:{isAvailable:!1}}}];
const day = 'Monday';
// Accepts the data and day as arguments
function finder(data, day) {
// For each object in the data...
return data.map(obj => {
// Destructure `name` and `workDays` from the object
const { name, workDays } = obj;
// Check to see if that day is available (making sure you
// render the day string to lower case)
const isAvailable = workDays[day.toLowerCase()].isAvailable;
// Return a new object that specifies the name, day, and
// availability as key/value pairs
return { name, day, isAvailable };
});
}
console.log(finder(workSchedule, day));
<!-- end snippet -->
Additional documentation
- In this example, we're using
reduce
to create an object that places the names of people in anisAvailable
array for a particular day.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const workSchedule=[{name:"a",age:21,workDays:{monday:{isAvailable:!0},tuesday:{isAvailable:!1},wednesday:{isAvailable:!0},thursday:{isAvailable:!0},friday:{isAvailable:!1}}},{name:"b",age:22,workDays:{monday:{isAvailable:!1},tuesday:{isAvailable:!1},wednesday:{isAvailable:!0},thursday:{isAvailable:!1},friday:{isAvailable:!1}}}];
const day = 'Monday';
// Accepts the data and day as arguments
function finder(data, day) {
// For each object in the data...
return data.reduce((acc, obj) => {
// Destructure `name` and `workDays` from the object
const { name, workDays } = obj;
// Create an object key using the lowercase'd day value
const key = day.toLowerCase();
// Check to see if that day is available
const { isAvailable } = workDays[key];
// If the day doesn't exist as a key on the output object
// add it and initialise it to an object with an empty
// `isAvailable` array
acc[key] ??= { isAvailable: [] };
// The day _is_ available add the name to the `isAvailable`
// array for that day
if (isAvailable) acc[key].isAvailable.push(name);
// Return the accumulator for the next iteration
return acc;
}, {});
}
console.log(finder(workSchedule, day));
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论