简体   繁体   English

遍历值 JavaScript 对象内的数组

[英]Loop through array inside a value JavaScript object

I have a Javascript project in which I am trying to iterate through an Array that is found as a value inside a property, to get the key and from this key get its values from another object.我有一个 Javascript 项目,在该项目中,我试图遍历一个在属性中作为值找到的数组,以获取键并从该键中从另一个对象获取其值。

Right now I can only get the key of the property that contains only one value, I need to get the key of the properties that have arrays as value.现在我只能获取只包含一个值的属性的键,我需要获取以数组为值的属性的键。

This is the input value:这是输入值:

let asset = "test";

This is the first object I need to get the key that the above value belongs to:这是我需要获取上述值所属的键的第一个对象:

let testData = {
  "data1": ["CAR,PLANE"],
  "data2":["COUNTRY,CITY"],
  "data3":"TEST"
};

This is the second object, from which I have to get the values depending on the previous key:这是第二个对象,我必须根据前一个键从中获取值:

let dataObj = {
  "data1": [
    "t1Data1",
    "t2Data1",
    "t3Data1"
  ],
  "data2": [
    "t1Data2",
    "t2Data2",
    "t3Data2"
  ],
  "data3": [
    "t1Data3",
    "t2Data3",
    "t3Data3"
  ]
};

This is what I do to get the key:这就是我获取密钥的方法:

let res = Object.keys(testData).find(key => testData[key] === asset.toUpperCase());

This is what it returns when the value is a single String:这是当值是单个字符串时它返回的内容:

data3

This is what it returns when the value is inside an array (let asset = "car";) :这是当值在数组中时返回的内容(let asset = "car";)

undefined

This is what I need:这就是我需要的:

data1

This is what I do to iterate through the array:这就是我遍历数组的方法:

for(let getData of testData.data1) {
  console.log(getData)
}

I need to iterate through the array when getting the key, but I don't know how to include this in the res variable.获取密钥时我需要遍历数组,但我不知道如何将其包含在 res 变量中。

You can convert string values into array, while leaving array values unchanged and then use Array#includes and Array#find methods as follows:您可以将字符串值转换为数组,同时保持数组值不变,然后使用Array#includesArray#find方法,如下所示:

 const asset = "test", dataObj = { "data1": ["CAR","TRUCK","TRAIN"], "data2": ["PLANT","TREE","SEEDLING"], "data3": "TEST" }, output = (o,k) => (Object.entries(o).find( ([key,value]) => [].concat(...[value]).includes(k.toUpperCase()) ) || ['NOT FOUND'])[0]; console.log( output(dataObj,asset) ); console.log( output(dataObj,"car") ); console.log( output(dataObj,"skooter") );

也许你可以尝试这样的事情?

let res = Object.keys(testData).find(key => typeof testData[key] === 'object' ? testData[key].includes(asset.toUpperCase()) : testData[key] === asset.toUpperCase());

Presented below is one possible way to achieve the desired objective.下面介绍的是实现预期目标的一种可能方式。

Code Snippet代码片段

 // method to find the key const findKeyFor = (val, obj) => ( // iterate over key-value pairs of given object 'obj' Object.entries(obj) // find key-value pair where // value matches the "asset" .find(([k, v]) => [v].flat().some( // [v].flat() accounts for value in "testData" // being either string or array of string elt => elt.split(',').some( // "elt.split()" accounts for string separated // by comma such as "CAR,PLANE" w => w === val.toUpperCase() ) )) ?.[0] // extract only the "key" ?? 'not found' // if not found, ); const testData = { "data1": ["CAR,PLANE"], "data2":["COUNTRY,CITY"], "data3":"TEST" }; let asset1 = 'test'; let asset2 = 'car'; console.log( 'find key for "test": ', findKeyFor(asset1, testData) ); console.log( 'find key for "car": ', findKeyFor(asset2, testData) ); let dataObj = { "data1": [ "t1Data1", "t2Data1", "t3Data1" ], "data2": [ "t1Data2", "t2Data2", "t3Data2" ], "data3": [ "t1Data3", "t2Data3", "t3Data3" ] }; // to get the value from "dataObj" using the above method console.log( 'get dataObj array for "test": ', dataObj?.[findKeyFor('test', testData)] ); console.log( 'get dataObj array for "car": ', dataObj?.[findKeyFor('car', testData)] );
 .as-console-wrapper { max-height: 100% !important; top: 0 }

Explanation解释

Inline comments added to the snippet above.添加到上述代码段的内联注释。

You need to go through each item in the array:您需要遍历数组中的每个项目:

 let dataObj = { data1: ['t1Data1', 't2Data1', 't3Data1'], data2: ['t1Data2', 't2Data2', 't3Data2'], data3: ['t1Data3', 't2Data3', 't3Data3'], }; let testData = { data1: ['CAR,PLANE'], data2: ['COUNTRY,CITY'], data3: 'TEST', }; let asset = 'car'; let res = Object.keys(testData).find(key => { const value = testData[key] if (Array.isArray(value)) { // Go through each item in the array and compare return value.some(item => item.toLowerCase().includes(asset)) } return value.toLowerCase().includes(asset) }) console.log(res);

The value of data1 is ["CAR,PLANE"] . data1的值为["CAR,PLANE"] A single element in an array.数组中的单个元素。 Your logic assumes "CAR" and "PLANE" are 2 individual string elements of an array.您的逻辑假设“CAR”和“PLANE”是数组的 2 个单独的字符串元素。 You can change your code to the following (assuming you always have a single element in the array).您可以将代码更改为以下内容(假设数组中始终只有一个元素)。

let dataObj = {
  data1: ['t1Data1', 't2Data1', 't3Data1'],
  data2: ['t1Data2', 't2Data2', 't3Data2'],
  data3: ['t1Data3', 't2Data3', 't3Data3'],
};

let testData = {
  data1: ['CAR,PLANE'],
  data2: ['COUNTRY,CITY'],
  data3: 'TEST',
};

let asset = 'car';

let res = Object.keys(testData).find((key) =>
  typeof testData[key] === 'object'
    ? testData[key][0].includes(asset.toUpperCase())
    : testData[key] === asset.toUpperCase()
);

console.log(res);

Notice the [0] in ? testData[key][0].includes(asset.toUpperCase())注意[0]中的? testData[key][0].includes(asset.toUpperCase()) ? testData[key][0].includes(asset.toUpperCase()) . ? testData[key][0].includes(asset.toUpperCase())

If your example is wrong and ["CAR,PLANE"] should really be ["CAR", "PLANE"] , I believe your code should work.如果您的示例错误并且["CAR,PLANE"]应该真的是["CAR", "PLANE"] ,我相信您的代码应该可以工作。

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

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