typescript 分割对象键值中的逗号并读取值

uttx8gqw  于 12个月前  发布在  TypeScript
关注(0)|答案(3)|浏览(192)

我有一个对象数组,其中一些键值是在逗号分隔设置在这里下面是样本对象是如何

var data = [{
  "id":1,
  "x, y, z" :"1,2,3"
}, {
  "id":2,
  "x, y, z" :"10,12,153"
}, {
  "id":3,
  "x, y, z" :"9,8,5"
}, {
  "id":4,
  "x, y, z" :"14,87,13"
}]

字符串
这是预期的输出

[{
  "id":1,
  "x":1,
  "y":2,
  "z":3
},{
  "id":2,
  "x":10,
  "y":12,
  "z":153
},{
  "id":3,
  "x":9,
  "y":8,
  "z":5
},{
  "id":4,
  "x":14,
  "y":87,
  "z":13
}]


下面是我尝试的代码,

const outputArray = data.map((item:any, index:number) => {
      let commaHeaders = Object.keys(item)[index]?.split(',');
      console.log(commaHeaders)
      if(commaHeaders && commaHeaders.length >= 2) {
        commaHeaders.map((comma) =>{
          item[comma] = comma.trim();
        })
      }
      return item
});

注意函数应该是通用的,在某些情况下我会得到a,b,c作为键值而不是x,y,z任何帮助或建议都很有帮助!

x4shl7ld

x4shl7ld1#

比如说:

function decommafy(obj) {
  const newObj = {};
  for (const [key, value] of Object.entries(obj)) {
    if (key.includes(",") && typeof value === "string") {
      const keys = key.split(",");
      const values = value.split(",");
      for (let i = 0; i < keys.length; i++) {
        newObj[keys[i].trim()] = values[i].trim();
      }
    } else {
      newObj[key] = value;
    }
  }
  return newObj;
}

const result = [
  {
    id: 1,
    "x, y, z": "1,2,3",
  },
  {
    id: 2,
    "fnef, fnerdl": "farb,forb",
    "zub,zab": "zeeb,zib",
  },
].map(decommafy);

console.log(result);

字符串
这不会自动将值转换为Numbers,但您可以简单地添加它。

dba5bblo

dba5bblo2#

您可以拆分所有键/值对(通过逗号和可选空格)并将有限值转换为数字。

const
    data = [{ "id": 1, "x, y, z": "1,2,3" }, { "id": 2, "x, y, z": "10,12,153" }, { "id": 3, "x, y, z": "9,8,5" }, { "id": 4, "x, y, z": "14,87,13" }],
    result = data.map(o => Object.fromEntries(Object
        .entries(o)
        .flatMap(([k, v]) => {
            const
                kk = k.split(/\s*,\s*/),
                vv = v.toString().split(/\s*,\s*/).map(v => isFinite(v) ? +v : v);
                
            return kk.map((k, i) => [k, vv[i]]);
        })    
    ));

console.log(result);

个字符

du7egjpx

du7egjpx3#

像这样的东西应该能用

const outputArray = data.map((item) => {
      // Extract the keys of item
      let keys = Object.keys(item);
      // Find the key with comma
      const commaKey = keys.find((key) => key.includes(','));
      // Extract the properties
      const commaHeaders = commaKey.split(', ');
      // Extract the values
      const commaValues = items[commaKey].split(', ');
      // Assign the right value to the right key in item
      commaHeaders.forEach((key, index) => {
        item[key] = commaValues[index];
      });
      // Delete the original property
      delete item[commaKey];
      return item
});

字符串

相关问题