如何将数组转换为对象

时间:2019-10-19 14:45:33

标签: javascript arrays filter

我正在尝试将人的对象数组过滤到一个新对象中,其属性名称按年龄排列在单独的数组中。

示例1

输入:

groupAdultsByAgeRange([{name: "Henry", age: 9}, {name: "John", age: 20}])

结果:

{ '20 and younger': [ { name: 'John', age: 20 } ] }

示例2

输入:

groupAdultsByAgeRange([{name: "Anna", age: 31}, {name: "John", age: 32}, {name: "Hank", age: 60}])

结果:

{ 
  '31-40': [ { name: 'Anna', age: 31 }, { name: 'John', age: 32 } ],
  '51 and older': [ { name: 'Hank', age: 60 } ] 
}

如果年龄范围不在输入范围之内,则不应成为输出范围的一部分。例如,如果输入的年龄不超过51岁,则该对象不应包含“ 51岁以上”的属性。并且如果输入我们为空数组,则输出应为空对象。

3 个答案:

答案 0 :(得分:0)

使用lodash,您可以执行以下操作

const _ = require('lodash');

const array = [{name: "Anna", age: 31}, {name: "John", age: 32}, {name: "Hank", age: 60}];

function ageToRange(obj) {
  const age = obj.age;
  if (age <= 20) {
    return '20 and younger';
  } 
  if (age > 30 && age <= 40) {
    return '31-40'
  }
  if (age > 50) {
    return '51 and older';
  }
}

const result = _.groupBy(array, ageToRange)

console.log(result);

答案 1 :(得分:0)

这是使用本地Javascript的方法:

//example 1
		let people1 = [{name: "Henry", age: 9}, {name: "John", age: 20}]
		let younger_and_equal_20 = []
		people1.forEach(e => {
			if(e.age>=20){
				younger_and_equal_20.push(e)
			}
		}); 
		console.log({"20 and younger": younger_and_equal_20})

		//example 2
		let people2 = [{name: "Anna", age: 31}, {name: "John", age: 32}, {name: "Hank", age: 60}]
		let data = {
			"31-40" : [],
			"51 and older" : []
		}
		people2.forEach(e => {
			if(e.age>30 && e.age<=40){
				data["31-40"].push(e)
			}
			else if(e.age>50){
				data["51 and older"].push(e)
			}
		});
		console.log(data)

答案 2 :(得分:0)

    let result = {}

    function groupAdultsByAgeRange(people) {
        // An array of object which represents people who are 20 or younger
        const ageGroup = people.filter(person => person.age <= 20)

        // Only add array to the object key if it's not empty
        if (ageGroup.length > 0) {
            result["20 and younger"] = ageGroup
        }

        return result;
    }