我试图使用javascript从json文件中获取中值

时间:2017-10-15 06:55:07

标签: javascript json

尝试从年龄中提取平均值并在其中一个年龄中处理缺失值。

var data={"users":[
{
"first_name":"Mikey",
"last_name":"Mouse",
"age": 24
},
{
"first_name":"Donald",
"lastName":"Duck",
"age": 29
},
{
"first_name":"Woody",
"lastName":"Woodpecker",
"age":
},
{
"first_name":"Bugs",
"lastName":"Bunny",
"age": 32
}  
]}

3 个答案:

答案 0 :(得分:0)

使用Ramda,您可以执行以下操作(不知道您使用的是哪些库,您没有提供任何代码):

const ages = R.compose(R.map(R.propOr(0, 'age')), R.propOr([], 'users'))
const mean = R.converge(R.divide, [R.sum, R.length])
const meanAges = R.compose(mean, ages)

console.log(meanAges(data)) // 21.25
如果没有给予年龄,

R.propOr(0, 'age')0作为年龄。

const data={"users":[
{
"first_name":"Mikey",
"last_name":"Mouse",
"age": 24
},
{
"first_name":"Donald",
"lastName":"Duck",
"age": 29
},
{
"first_name":"Woody",
"lastName":"Woodpecker"
},
{
"first_name":"Bugs",
"lastName":"Bunny",
"age": 32
}  
]}

const ages = R.compose(R.map(R.propOr(0, 'age')), R.propOr([], 'users'))
const mean = R.converge(R.divide, [R.sum, R.length])
const meanAges = R.compose(mean, ages)

console.log(meanAges(data))
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.22.1/ramda.min.js"></script>

答案 1 :(得分:0)

删除没有设定年龄的人,然后映射以获得年龄,然后排序并返回美联储:

function getMedeanAge(data) {
    let ages = data
        .filter(cartoon => cartoon.age !== undefined)
        .map(cartoon => cartoon.age)
        .sort((a,b) => a > b);

    var middleIndex = ages.length / 2;

    return ages[Math.floor(middleIndex)] + ages[Math.ceil(middleIndex) / 2;
}

答案 2 :(得分:0)

通过收集sum中的所有值和有效age的计数,您可以使用Array#forEach的单循环方法。然后,您可以按所有年龄段的总和除以count得到平均值。

&#13;
&#13;
var data = { users: [{ first_name: "Mikey", last_name: "Mouse", age: 24 }, { first_name: "Donald", lastName: "Duck", age: 29 }, { first_name: "Woody", lastName: "Woodpecker", age: null }, { first_name: "Bugs", lastName: "Bunny", age: 32 }] },
    sum = 0,
    count = 0,
    average;

data.users.forEach(function (user) {
    if (typeof user.age === 'number') {
        sum += user.age;
        ++count;
    }
});

average = sum / count;

console.log(average);
&#13;
&#13;
&#13;