I want to filter array of objects with a string that should match with a objects property key and should check that key value

huangapple go评论137阅读模式
英文:

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: &quot;a&quot;,
      age: 21,
      workDays: {
        monday: { isavailable: true },
        tuesday: { isavailable: false },
        wednesday: { isavailable: true },
        thursday: { isavailable: true },
        friday: { isavailable: false },
      },
    },
    {
      name: &quot;b&quot;,
      age: 22,
      workDays: {
        monday: { isavailable: false },
        tuesday: { isavailable: false },
        wednesday: { isavailable: true },
        thursday: { isavailable: false },
        friday: { isavailable: false },
      },
    },
  ];

  const day = &quot;Monday&quot;;

  workSchedule.forEach((e) =&gt; {
    if (e.workDays[day.toLocaleLowerCase()][&quot;isavailable&quot;]) {
      console.log(e.name + &quot; is available&quot;);
    } else {
      console.log(e.name + &quot; is not available&quot;);
    }
  });

<!-- 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: &#39;a&#39;,
			age: 21,
			workDays: {
			  monday: { isavailable: true },
			  tuesday: { isavailable: false },
			  wednesday: { isavailable: true },
			  thursday: { isavailable: true },
			  friday: { isavailable: false }
			}
		  },
		  {
			name: &#39;b&#39;,
			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 =&gt; {
			  if (
				person.workDays &amp;&amp;
				person.workDays.hasOwnProperty(lowercaseDay) &amp;&amp;
				person.workDays[lowercaseDay].isavailable
			  ) {
				availablePersons.push(person);
			  }
			});

			// Display available persons
			console.log(`available persons on ${day}: (${availablePersons.length})`);
			availablePersons.forEach(person =&gt; {
			  console.log(`- ${person.name}`);
			});
		}
		
		getAvailablePersons(&#39;Monday&#39;);
		getAvailablePersons(&#39;Wednesday&#39;);

<!-- 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: &#39;a&#39;,
			age: 21,
			workDays: {
			  monday: { isavailable: true },
			  tuesday: { isavailable: false },
			  wednesday: { isavailable: true },
			  thursday: { isavailable: true },
			  friday: { isavailable: false }
			}
		  },
		  {
			name: &#39;b&#39;,
			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 =&gt; {
			  if (
				person.workDays &amp;&amp;
				person.workDays.hasOwnProperty(lowercaseDay) &amp;&amp;
				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 =&gt; {
			  console.log(`- ${person.name}`);
			});
		}
		
		day = &#39;Monday&#39;;
		let personsOnMonday = getAvailablePersons(day);
		console.log(personsOnMonday);
		listPersons(day);
		
		day = &#39;Wednesday&#39;;
		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 = &#39;monday&#39;;
        const workSchedule = [
        {
            name: &#39;a&#39;,
            age: 21,
            workDays: {
                monday: {isavailable:true}, tuesday:{isavailable:false}, wednesday:{isavailable:true}, thursday:{isavailable:true}, Friday:{isavailable:false}
            }
        },
        {
            name: &#39;b&#39;,
            age: 22,
            workDays: {
                monday: {isavailable:false}, tuesday:{isavailable:false}, wednesday:{isavailable:true}, thursday:{isavailable:false}, Friday:{isavailable:false}
            }
        }
    ];

    
const available = workSchedule.filter(sch=&gt; sch.workDays[day.toLowerCase()].isavailable === true);


console.log(available[0]);
console.log(available[0].name);

<!-- end snippet -->

答案4

得分: 0

首先,你应该标准化你的输入数据,以使其一致(例如,使用 friday 而不是 Friday,以及 isAvailable 而不是 isavailable)。

答案取决于你期望的输出数据类型。这将决定数据查询和操作的方式。

以下是几个示例。


  1. 使用 filtermap 来创建一个名字数组,我们可以将其赋值给名为 isAvailableOnMonday 的变量。
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);

  1. 在这个示例中,我们只是使用 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));

  1. 在这个示例中,我们使用 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.


  1. Using filter and map to create an array of names we can assign to a variable called isAvailableOnMonday.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const workSchedule=[{name:&quot;a&quot;,age:21,workDays:{monday:{isAvailable:!0},tuesday:{isAvailable:!1},wednesday:{isAvailable:!0},thursday:{isAvailable:!0},friday:{isAvailable:!1}}},{name:&quot;b&quot;,age:22,workDays:{monday:{isAvailable:!1},tuesday:{isAvailable:!1},wednesday:{isAvailable:!0},thursday:{isAvailable:!1},friday:{isAvailable:!1}}}];
const day = &#39;Monday&#39;;

// Accepts the data and day as arguments
function finder(data, day) {

  // For each object in the data...
  return data.filter(obj =&gt; {

    // 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 =&gt; obj.name);

}

const isAvailableOnMonday = finder(workSchedule, day);
console.log(isAvailableOnMonday);

<!-- end snippet -->


  1. 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 day isAvailable.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const workSchedule=[{name:&quot;a&quot;,age:21,workDays:{monday:{isAvailable:!0},tuesday:{isAvailable:!1},wednesday:{isAvailable:!0},thursday:{isAvailable:!0},friday:{isAvailable:!1}}},{name:&quot;b&quot;,age:22,workDays:{monday:{isAvailable:!1},tuesday:{isAvailable:!1},wednesday:{isAvailable:!0},thursday:{isAvailable:!1},friday:{isAvailable:!1}}}];
const day = &#39;Monday&#39;;

// Accepts the data and day as arguments
function finder(data, day) {

  // For each object in the data...
  return data.map(obj =&gt; {

    // 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


  1. In this example, we're using reduce to create an object that places the names of people in an isAvailable array for a particular day.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const workSchedule=[{name:&quot;a&quot;,age:21,workDays:{monday:{isAvailable:!0},tuesday:{isAvailable:!1},wednesday:{isAvailable:!0},thursday:{isAvailable:!0},friday:{isAvailable:!1}}},{name:&quot;b&quot;,age:22,workDays:{monday:{isAvailable:!1},tuesday:{isAvailable:!1},wednesday:{isAvailable:!0},thursday:{isAvailable:!1},friday:{isAvailable:!1}}}];
const day = &#39;Monday&#39;;

// Accepts the data and day as arguments
function finder(data, day) {

  // For each object in the data...
  return data.reduce((acc, obj) =&gt; {

    // Destructure `name` and `workDays` from the object
    const { name, workDays } = obj;

    // Create an object key using the lowercase&#39;d day value
    const key = day.toLowerCase();

    // Check to see if that day is available
    const { isAvailable } = workDays[key];

    // If the day doesn&#39;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 -->

huangapple
  • 本文由 发表于 2023年5月25日 19:23:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76331739.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定