在值 JavaScript 对象内循环遍历数组

Loop through array inside a value JavaScript object

我有一个 Javascript 项目,我试图在其中迭代一个数组,该数组在 属性 中作为一个值被发现, 获取密钥并从此密钥从另一个对象获取其值。

现在我只能获取到只有一个值的属性的键,我需要获取以数组为值的属性的键

这是输入值:

let asset = "test";

这是我需要获取上述值所属的键的第一个对象:

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

这是第二个对象,我必须根据前一个键从中获取值:

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

这是我获取密钥的方式:

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

当值是单个字符串时,returns就是这样:

data3

当值在数组中时 returns 就是这样 (let asset = "car";):

undefined

这是我需要的:

data1

这是我循环访问数组的方法:

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

我需要在获取密钥时遍历数组,但我不知道如何将其包含在res变量中。

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

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

您可以将字符串值转换为数组,同时保持数组值不变,然后使用 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") );

下面介绍的是实现所需 objective.

的一种可能方法

代码段

// 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 }

说明

在上面的代码段中添加了内联评论。

您需要遍历数组中的每一项:

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);

data1的值为["CAR,PLANE"]。数组中的单个元素。您的逻辑假设“CAR”和“PLANE”是一个数组的 2 个单独的字符串元素。您可以将代码更改为以下内容(假设数组中始终只有一个元素)。

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);

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

如果您的示例是错误的并且 ["CAR,PLANE"] 确实应该是 ["CAR", "PLANE"],我相信您的代码应该可以工作。