json 如何根据输入值查找出现次数

7qhs6swi  于 4个月前  发布在  其他
关注(0)|答案(3)|浏览(74)

我试图根据下面的JavaScript Json Object中的ownerId的输入值来查找出现的次数。如果ownerId是数字“1”,则结果应该是3,因为ownerId出现了3次。

ownerID: 3

字符串
这就是我目前所拥有的...

let inputValue = 1;
let return = "";

const result = jsonResponse.jsonArray[0].info.find(
(arr) => arr.ownderID === inputValue;  );
    
var data = jsonResponse.jsonArray[0].info
        .reduce((counts, result) => {
        const inputItem = result[inputValue];
        counts[inputItem] = (counts[inputItem] || 0) + 1;
        return counts;
      }, {
      });

    return = data;


JSON.

const jsonResponse = {
   "jsonArray": [
     {
        "info": [
            {
                "ownerId": 1,
                "carType": "Nissan",
                "houseType": "Rancher"
            },
            {
                "ownerId": 1,
                "carType": "Ford",
                "houseType": "Trailer"
            }
        ],
        "familyInfo": {
            "kids": 1,
            "tuition": "yes",
            "parentId": 7
        }
    },
    {
        "info": [
            {
                "ownerId": 3,
                "carType": "Nissan",
                "houseType": "Single"
            }
        ],
        "familyInfo": {
            "kids": 4,
            "tuition": "no",
            "parentId": 11
        }
    },
    {
        "info": [
            {
                "ownerId": 1,
                "carType": "Chevy",
                "houseType": "TownHome"
            }
        ]
    }
  ]
}


我使用find和reduce的方法正确吗?

58wvjzkj

58wvjzkj1#

您几乎已经完成了,您需要做的是在多个jsonArrays上计数,并在info内计数
看看下面的代码,我已经适当地注解了它,使它变得冗长。希望它能有所帮助。

const jsonResponse = {
  "jsonArray": [{
      "info": [{
          "ownerId": 1,
          "carType": "Nissan",
          "houseType": "Rancher"
        },
        {
          "ownerId": 1,
          "carType": "Ford",
          "houseType": "Trailer"
        }
      ],
      "familyInfo": {
        "kids": 1,
        "tuition": "yes",
        "parentId": 7
      }
    },
    {
      "info": [{
        "ownerId": 3,
        "carType": "Nissan",
        "houseType": "Single"
      }],
      "familyInfo": {
        "kids": 4,
        "tuition": "no",
        "parentId": 11
      }
    },
    {
      "info": [{
        "ownerId": 1,
        "carType": "Chevy",
        "houseType": "TownHome"
      }]
    }
  ]
}

// what to search for?
const searchOwnerId = 1;

// reduce to count owner id across multiple items in the list
const counts = jsonResponse.jsonArray.reduce((acc, item) => {
  // count the owner ids inside the infos
  // filter for the ownerId and length works perfect
  
  acc += item.info.filter(
    ({ownerId}) => ownerId == searchOwnerId
  ).length

  return acc

// start reduce with a zero
}, 0);

// final output
console.log(counts)

字符串

sg3maiej

sg3maiej2#

你也可以使用forEach循环或reduce,就像在其他答案中给出的那样,这两种方法都很好。

const jsonResponse = {
  jsonArray: [
    {
      info: [
        {
          ownerId: 1,
          carType: "Nissan",
          houseType: "Rancher",
        },
        {
          ownerId: 1,
          carType: "Ford",
          houseType: "Trailer",
        },
      ],
      familyInfo: {
        kids: 1,
        tuition: "yes",
        parentId: 7,
      },
    },
    {
      info: [
        {
          ownerId: 3,
          carType: "Nissan",
          houseType: "Single",
        },
      ],
      familyInfo: {
        kids: 4,
        tuition: "no",
        parentId: 11,
      },
    },
    {
      info: [
        {
          ownerId: 1,
          carType: "Chevy",
          houseType: "TownHome",
        },
      ],
    },
  ],
};
function countOccurrences(jsonResponse, inputValue) {
  let resultCount = 0;

  jsonResponse.jsonArray.forEach((item) => {
    if (item.info) {
      resultCount += item.info.filter(
        (info) => info.ownerId === inputValue
      ).length;
    }
  });

  return resultCount;
}

const inputValue = 1;
const result = countOccurrences(jsonResponse, inputValue);
console.log(result);

字符串

6qfn3psc

6qfn3psc3#

如果你熟悉@ut8pia/classifier库,你就会知道,通过使用queue和search space作为函数返回每个已探索对象的所有子对象,探索嵌套对象变得很简单。

const 
    space = node => node.children,
    search = new ArrayQueue()
        .let(root)
            .search(space)

字符串
方法search(space)导航root节点的所有后代。要返回的是迭代的形式定义,提供进一步的方法来限制,组合,转换和解析迭代。
让我们应用这个称为“搜索和选择”模式的范例,来定义一个函数n(key, value, root),该函数计算具有指定key属性的value嵌套对象的出现次数。

function n(key, value, root) {
    const
        space = node => typeof(node) === 'string'? []
            : Object.values(node),

        search = new ArrayQueue()
            .let(root)
                .search(space)
                    .which(obj => obj[key]===value),

        got = search
            .what((n, _) => n+1, 0);

    return got
}


方法which(predicate)search限制为满足predicate的对象,而方法what(op, start)解析search。这些方法类似于Array类中的方法filter(predicate)reduce(op, start),但设计为即使在涉及无限迭代的情况下也适用(请参阅图书馆的在线文档)。
您可以通过以下方式检查建议解决方案的有效性:

import { ArrayQueue } from "@ut8pia/classifier/queue/ArrayQueue.js";
import assert from "assert";

    const data = {
        "jsonArray": [
          {
             "info": [
                 {
                     "ownerId": 1,
                     "carType": "Nissan",
                     "houseType": "Rancher"
                 },
                 {
                     "ownerId": 1,
                     "carType": "Ford",
                     "houseType": "Trailer"
                 }
             ],
             "familyInfo": {
                 "kids": 1,
                 "tuition": "yes",
                 "parentId": 7
             }
         },
         {
             "info": [
                 {
                     "ownerId": 3,
                     "carType": "Nissan",
                     "houseType": "Single"
                 }
             ],
             "familyInfo": {
                 "kids": 4,
                 "tuition": "no",
                 "parentId": 11
             }
         },
         {
             "info": [
                 {
                     "ownerId": 1,
                     "carType": "Chevy",
                     "houseType": "TownHome"
                 }
             ]
         }
       ]
     },

     got = n('ownerId', 1, data),

     expected = 3;

assert.equal(got, expected)

相关问题