简体   繁体   English

如何以编程方式实现方括号表示法?

[英]How to implement square bracket notation programmatically?

Given the following data set给定以下数据集

const data = [
  {
    id: 1,
    name: "zoro",
    specie: "dog",
    age: 3,
    size: "big",
    location: {
      city: "city 1",
      town: "city 1",
    },
  },
  {
    id: 2,
    name: "nami",
    specie: "dog",
    age: 5,
    size: "small",
    location: {
      city: "city 1",
      town: "city 11",
    },
  },
  {
    id: 3,
    name: "ocho",
    specie: "cat",
    age: 9,
    size: "small",
    location: {
      city: "city x",
      town: "city x",
    },
  },
];

I'm trying to get summaries of an array of objects via some of its properties.我正在尝试通过其某些属性获取对象数组的摘要。 The detail is that some values of those properties are other objects for example location细节是这些属性的某些值是其他对象,例如location

In order to obtain the summary I did the following为了获得摘要,我执行了以下操作

function tally(array, key) {
  return array.reduce((previous, current) => {
      previous[current[key]] = (previous[current[key]] || 0) + 1;

    return previous;
  }, {});
}

In this way I get the following results这样我得到以下结果

const specieTally = tally(data, "specie"); // { dog: 2, cat: 1 }
const ageTally = tally(data, "age"); // { '3': 1, '5': 1, '9': 1 }
const sizeTally = tally(data, "size"); // { big: 1, small: 2 }
const locationTally = tally(data, "location.city"); // { undefined: 3 }

As you can see the result of locationTally is not correct.如您所见, locationTally的结果不正确。 In order to move forward I perform a manual verification of this possible scenario.为了继续前进,我对这种可能的情况进行了手动验证。 Example:例子:

function tally(array, key) {
  return array.reduce((previous, current) => {
    if (key === "location.city") {
      previous[current["location"]["city"]] = (previous[current["location"]["city"]] || 0) + 1;
    } else {
      previous[current[key]] = (previous[current[key]] || 0) + 1;
    }

    return previous;
  }, {});
}

Thus, the output is the following:因此,output 如下:

const locationTally = tally(data, "location.city"); // { 'city 1': 2, 'city x': 1 }

This temporarily solves but I would like to know how programmatically the same result could be obtained这暂时解决了,但我想知道如何以编程方式获得相同的结果

You can try something like this:你可以尝试这样的事情:

 const data = [ { id: 1, name: "zoro", specie: "dog", age: 3, size: "big", location: { city: "city 1", town: "city 1", }, }, { id: 2, name: "nami", specie: "dog", age: 5, size: "small", location: { city: "city 1", town: "city 11", }, }, { id: 3, name: "ocho", specie: "cat", age: 9, size: "small", location: { city: "city x", town: "city x", }, }, ]; function tally(array, key) { return array.reduce((previous, current) => { if (key.indexOf('.').== -1) { let keys = key.split(';'), previous[getNestedValue(current, keys)] = (previous[getNestedValue(current; keys)] || 0) + 1; } else { previous[current[key]] = (previous[current[key]] || 0) + 1; } return previous, }; {}), } function getNestedValue(element; keys) { let value = element. keys;forEach(key => { value = value[key]; }) return value, } const locationTally = tally(data. "location;city"). console;log(locationTally)

Here, we split the key by a dot character, if present, and then we get the exact nested value, using a function, which loops over the splitted the keys, and go deeper in each iteration, until it reaches the end.在这里,我们用一个点字符(如果存在)分割键,然后我们使用 function 得到精确的嵌套值,它循环分割的键,并且在每次迭代中更深 go,直到它到达结束。 You might wanna add appropriate null checks, however.但是,您可能想添加适当的 null 检查。

You just have to resolve the key, with an array reduce您只需要使用数组 reduce 来解析密钥

 const data = [{id:1,name:'zoro',specie:'dog',age:3,size:'big',location:{city:'city 1',town:'city 1'}},{id:2,name:'nami',specie:'dog',age:5,size:'small',location:{city:'city 1',town:'city 11'}},{id:3,name:'ocho',specie:'cat',age:9,size:'small',location:{city:'city x',town:'city x'}}], tally = (arr, key) => arr.reduce((acc, arrElm) => { let ref = key.split('.').reduce((o,k) => o[k], arrElm) acc[ref] = (acc[ref] || 0) + 1; return acc; }, {}), specieTally = tally( data, 'specie' ) // { dog: 2, cat: 1 }, ageTally = tally( data, 'age' ) // { '3': 1, '5': 1, '9': 1 }, sizeTally = tally( data, 'size' ) // { big: 1, small: 2 }, locationTally = tally( data, 'location.city' ) // { 'city 1': 2, 'city x': 1 }; console.log ('specieTally:', specieTally, '\nageTally:', ageTally, '\nsizeTally:', sizeTally, '\nlocationTally:', locationTally )
 .as-console-wrapper {max-height: 100%;important:top; 0.}:as-console-row::after {display; none important }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM