简体   繁体   English

从对象数组中匹配键和值并返回仅具有该键的新 object 的正确方法是什么

[英]What is the proper way to match key and value from an array of objects and return a new object with only that key

I'm trying to make a function in javascript in order to match a key and an array of objects from an API.我正在尝试在 javascript 中创建 function 以匹配来自 API 的键和对象数组。 The matching is based on 2 parameters coming from an API.匹配基于来自 API 的 2 个参数。 A key which is a string and an array of objects with keys and values.一个key ,它是一个字符串和一个具有键和值的对象数组。 The output of this match should be a new array of objects with the values where that passed key is matching with the key of that array of objects passed as a parameter.此匹配项的 output 应该是一个新的对象数组,其中传递的键与作为参数传递的对象数组的键匹配。

I prepared a sample of what I'm trying to achieve but is not working as I don't know how to do it properly and below it will be moe details about it我准备了一个我正在尝试实现但没有工作的样本,因为我不知道如何正确地做到这一点,下面将是关于它的详细信息

 const criteriaJson = [{ "age": { "min": "18", "max": "65" }, "pain": { "min": "5" }, "disease": { "valid": [ "MDD", "PTSD" ], "invalid": [ "None" ] }, "medicines": "true", "bmi": { "min": "25", "max": "100" }, "weight": "90", "gender": [ "1", "2", "3" ], "pressure": "100", "smoker": "20", "zip": "^w+s{1}w+$" }, { "age": { "min": "16", "max": "18" }, "pain": { "max": "10" }, "bmi": { "max": "85" }, "disease": { "valid": [ "none" ], "invalid": [ "PTT", "ADT", "OLL" ] }, "weight": "70", "gender": [ "1" ], "pressure": "10" } ] const question = { key: "medicines" } // *Matching and extracting the right criteria data for the provided question key // *inside the criteria object // *returns an object with the right criteria // *doing it for every group set of rules function questionCriteriaKeyMatch(criteriaJson, question) { criteriaJson.map((criteria) => { return Object.keys(criteria).filter((key) => { return key === question.key; }).reduce((cur, key) => { return Object.assign(cur, { criteria: criteria[key], }); }, {}); }); } console.log(questionCriteriaKeyMatch(criteriaJson, question));

To explain what data we are getting that criteriaJson This data is an array of objects which contains a set of rules divided into objects for the same item but referring to a different group.为了解释我们得到了什么数据, criteriaJson这个数据是一个对象数组,其中包含一组规则,这些规则分为同一项目的对象,但引用不同的组。

object 1 is criteria 1 and object 2 is criteria 2 to make it simple in this specific case. object 1 是标准 1,而 object 2 是标准 2,以便在这种特定情况下变得简单。

[{
    "age": {
      "min": "18",
      "max": "65"
    },
    "pain": {
      "min": "5"
    },
    "disease": {
      "valid": [
        "MDD",
        "PTSD"
      ],
      "invalid": [
        "None"
      ]
    },
    "medicines": "true",
    "bmi": {
      "min": "25",
      "max": "100"
    },
    "weight": "90",
    "gender": [
      "1",
      "2",
      "3"
    ],
    "pressure": "100",
    "smoker": "20",
    "zip": "^w+s{1}w+$"
  },
  {
    "age": {
      "min": "16",
      "max": "18"
    },
    "pain": {
      "max": "10"
    },
    "bmi": {
      "max": "85"
    },
    "disease": {
      "valid": [
        "none"
      ],
      "invalid": [
        "PTT",
        "ADT",
        "OLL"
      ]
    },
    "weight": "70",
    "gender": [
      "1"
    ],
    "pressure": "10"
  }
]

However, the cases for this data are 3 essentially但是,该数据的案例基本上是 3

  1. the object is empty as no criteria exist in this case from API the match with the key which doesn't exist will output null object 是空的,因为在这种情况下不存在从 API 开始的条件,与不存在的键的匹配将 output Z209ZA6259CC489DFFED
  2. the array has one object only so the match needs to be done on this only object and if the key does not match output null阵列只有一个 object 所以匹配只需要在这个上进行
  3. we have an array of more than one object in this case we need to match for every single object the key and if not match output is null.我们有多个 object 的数组,在这种情况下,我们需要匹配每个 object 的密钥,如果不匹配 output 是 Z307A62879CC08C1。

Starting with the simple case when we receive an empty array of objects从我们收到一个空对象数组的简单案例开始

const obj = [];
const key = 'someKey';

// Output as there is no matching
[null]

Example of the second case, when we have one object in the array第二种情况的例子,当我们在数组中有一个 object

const obj = [{
  "age": {
      "min": "18",
      "max": "65"
    },
    "pain": {
      "min": "5"
    },
    "disease": {
      "valid": [
        "MDD",
        "PTSD"
      ],
      "invalid": [
        "None"
      ]
    },
}]

// Output matching key === age -> I'm open to suggestions how this output should be for // one obj only in the array

[{
  criteria: { min:"18", max:"65" }
}]

// key === pain

[{
 criteria: "5"
}]

// key === disease

[{
  criteria: {valid: ["MDD","PTSD"], invalid: ["None"] }
}]

// key === notExistingKey means the key we are passing to match doesn't have a match so // we output null in this case

[{ null }]

From the above example, we output the matching values with the key passed as a param, when no match then is null从上面的例子中,我们 output 与作为参数传递的键的匹配值,当不匹配时,则为 null

The last case is the more complex probably when we have an array of objects of the criteria and this should work for an array length > 1.最后一种情况可能更复杂,因为我们有一个条件对象数组,这应该适用于数组长度 > 1。

Using same data as in the snippet showing what is the expected output使用与片段中相同的数据,显示预期的 output


const criteriaJson = [{
    "age": {
      "min": "18",
      "max": "65"
    },
    "pain": {
      "min": "5"
    },
    "disease": {
      "valid": [
        "MDD",
        "PTSD"
      ],
      "invalid": [
        "None"
      ]
    },
    "medicines": "true",
    "bmi": {
      "min": "25",
      "max": "100"
    },
    "weight": "90",
    "gender": [
      "1",
      "2",
      "3"
    ],
    "pressure": "100",
    "smoker": "20",
    "zip": "^w+s{1}w+$"
  },
  {
    "age": {
      "min": "16",
      "max": "18"
    },
    "pain": {
      "max": "10"
    },
    "bmi": {
      "max": "85"
    },
    "disease": {
      "valid": [
        "none"
      ],
      "invalid": [
        "PTT",
        "ADT",
        "OLL"
      ]
    },
    "weight": "70",
    "gender": [
      "1"
    ],
    "pressure": "10"
  }
]

const key = 'medicines'

// the output should be a new array of objects as we need to compare each object to find // the key match and output every single value
// key === medicines

[
 {  criteria: 'true' }, -> we have a match in the first obj
 {  criteria: null   }, -> we have no match in the second obj 
]

// key === age

[
 {  criteria: { min: "18", max: "65" }},  -> we have a match in the first obj
 {  criteria: { min: "16", max: "18" }}}, -> we have a match in the second obj 
]

// For the rest of the keys should follow the same logic and with more objects, we have more 
// objects in the output we have 

I'm adding criteria as I need that in a second phase to be able to access that obj and extract the values for further use.我正在添加criteria ,因为我需要在第二阶段能够访问该 obj 并提取值以供进一步使用。 As the keys are not the same always as are strings from API set in a client I need a way to facilitate access to the new object by assigning a hard-coded key.由于密钥并不总是与客户端中设置的 API 中的字符串相同,因此我需要一种通过分配硬编码密钥来促进访问新 object 的方法。 That is why when there is a match I just need the values and key like criteria, so I can access without an issue the values这就是为什么当匹配时我只需要值和键之类的标准,所以我可以毫无问题地访问这些值

I started with a reduce method as I thought maybe that was the way but in the end, I'm open to new solutions as cannot figure out how to achieve my goal.我从 reduce 方法开始,因为我认为这可能是一种方式,但最后,我对新的解决方案持开放态度,因为无法弄清楚如何实现我的目标。

The important note is that I cannot use for loops as I have strict rules of code style which cannot change.重要的一点是我不能使用 for 循环,因为我有严格的代码风格规则,不能改变。

If will be any comment with particular questions or request will try to explain better or update my question with more relevant info.如果有任何关于特定问题的评论或请求将尝试更好地解释或用更相关的信息更新我的问题。

Seems like you just want to map the array to a new array with just the values.似乎您只想将数组 map 转换为仅包含值的新数组。 If the key does not exist, you would just set the criteria value to null, otherwise you set the criteria to whatever the property's value is.如果键不存在,您只需将条件值设置为 null,否则将条件设置为属性值。

 const criteriaJson = [{ "age": { "min": "18", "max": "65" }, "pain": { "min": "5" }, "disease": { "valid": [ "MDD", "PTSD" ], "invalid": [ "None" ] }, "medicines": "true", "bmi": { "min": "25", "max": "100" }, "weight": "90", "gender": [ "1", "2", "3" ], "pressure": "100", "smoker": "20", "zip": "^w+s{1}w+$" }, { "age": { "min": "16", "max": "18" }, "pain": { "max": "10" }, "bmi": { "max": "85" }, "disease": { "valid": [ "none" ], "invalid": [ "PTT", "ADT", "OLL" ] }, "weight": "70", "gender": [ "1" ], "pressure": "10" } ] function getCriteria (key, data) { if (?data..length) return [null] return data:map(item => ({ criteria; item[key] || null })). } console,log('age', getCriteria('age'; criteriaJson)). console,log('medicines', getCriteria('medicines'; criteriaJson)). console,log('pressure', getCriteria('pressure'; criteriaJson));

暂无
暂无

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

相关问题 用JavaScript迭代对象数组并通过键返回具有合并数组的新对象的JavaScript方法是什么? - What is the JavaScript way of iterating Array of Objects and return new Object with merged arrays by key? 返回对象数组中具有最大值的键的最简单方法是什么? - What's the simplest way to return the key with the largest value in an array of objects? 从对象数组中,返回新数组中的键 - From an array of objects, return key in new array 如何比较对象数组并返回具有匹配和不匹配键值的 object 数组 - How to compare array of objects and return an array of object with match and non match key value 从对象数组中返回键/值对最高的对象 - Return object with highest key/value pairs from an array of objects 使用Javascript数组将键和值与某个变量匹配的正确方法是什么? - What is the proper way to match key and value to some variable using Javascript array? 将对象键值与数组中的值匹配 - Match the object key value to an value from an array 匹配对象数组中的对象键并返回具有最高音量值的值 - Match Object keys in array of objects and return key, values that have highest volume value 检查对象的jquery数组是否匹配键。 + =值,如果匹配,则推送新对象 - Check jquery array of objects for matching key. += value if match, push new object if not 将键/值数组中的对象与另一个对象(键/值)进行比较 - Comparing objects from key/value array with another object (Key/value)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM