[英]How to get all keys and values of an array using array functions
Using this array使用这个数组
const university = [
{ Students: 4, Lecturers: 15, Faculty: 'Mathematics' },
{ Students: 4, Lecturers: 15, Faculty: 'English' },
{ Students: 4, Lecturers: 15, Faculty: 'Science'}
]
I want to return all values with a certain key:我想用某个键返回所有值:
const students = [
{ Students: 4 },
{ Students: 4 },
{ Students: 4 }
]
I know I can do this with a for in loop:我知道我可以用 for in 循环来做到这一点:
for (const property in object) {
console.log(`${property}: ${object[property]}`);
}
Is there anyway to achieve this with map
, filter
, find
or reduce
?有没有办法用
map
、 filter
、 find
或reduce
来实现这一点? I can not seem to get the key out我好像拿不出钥匙
Answer:回答:
university.map(data => `Students: ${data.Students}`);
You could extract to a function.你可以提取到一个函数。
getByKey(arr, val) {
arr.map(data => `${val}: ${data[val]}`);
}
getKey(university, Faculty)
You can make use of map
and inside map
you can pass keys in array(which you want to pick) and take fromEntries
to form the object.您可以使用
map
和内部map
您可以在数组(您想要选择的)中传递键并使用fromEntries
来形成对象。
const university = [ { Students: 4, Lecturers: 15, Faculty: 'Mathematics' }, { Students: 4,Lecturers: 15, Faculty: 'English'} , { Students: 4, Lecturers: 15, Faculty: 'Science' } ]; const getGivenKeys=(arr,keys)=> arr.map(o=>Object.fromEntries(keys.map(k=>[k,o[k]]))); console.log(getGivenKeys(university, ['Students', 'Faculty'])); console.log(getGivenKeys(university, ['Students']));
Your key in that case is Students.在这种情况下,您的关键是学生。 So, you can do a map and return a new object with just that key.
因此,您可以执行映射并仅使用该键返回一个新对象。
const university = [{ Students: 46, Lecturers: 2, Faculty: 'Mathematics' }, { Students: 65, Lecturers: 6, Faculty: 'English' }, { Students: 48, Lecturers: 4, Faculty: 'Science' }] let result = []; result = university.map(obj => { return { Students: obj.Students } }); console.log(result)
You can use map() with a clean solution:您可以将 map() 与干净的解决方案一起使用:
const students = university.map(function(r){
return {"Students" : r.Students};
});
使用map
函数,但没有return
关键字:
university.map(uni=>({Students:uni.Students}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.