如何将用管道连接的数组中具有 属性 值的对象转换为逗号分隔

How to turn an object that has property values inside an array joined with pipe into comma separated

我有一个对象具有这样的值

const objectValues = {
    weight: ["0|5"],
    species: ["human|alien"],
    colour: ["Blue-Green|Red|Black|Orange With Green, Red, Yellow And Blue Play Of Colour"],
    shape: ["Rough"],
    uniqueId: "kobe"
}

我想把它变成一个像这样的对象:

const desiredObject = {
    weight: ["0","5"],
    species: ["human","alien"],
    colour: ["Blue-Green","Red","Black","Orange With Green, Red, Yellow And Blue Play Of Colour"],
    shape: ["Rough"],
    uniqueId: "kobe"
}

我认为我写的这个函数可以做到:

  let pipeToCommaObject = {};

  const mapSplitted = Object.keys(objectValues).map(key => {
    if(objectValues[key].join().includes('|')){
      pipeToCommaObject[key] = objectValues[key].join().split('|');
    }
  });

然而它并没有完全做到,请告知我缺少什么以及我需要什么 change/add 以获得我想要的结果。我认为问题可能在于 uniqueId 本身只是一个字符串,而所有其他属性都在一个数组中。我需要它按原样保留字符串,但对数组值进行操作。

你可以像这样使用 for

const object = {
  weight: ["0|5"],
  species: ["human|alien"],
  colour: [
    "Blue-Green|Red|Black|Orange With Green, Red, Yellow And Blue Play Of Colour",
  ],
  shape: ["Rough"],
  uniqueId: "kobe",
};

const newObject = {};

for (let key in object) {
  const property = object[key];
  //Check if element is an Array
  if (Array.isArray(property)) {
    //Split the first element
    newObject[key] = property[0].split("|");
  } else {
    newObject[key] = property;
  }

}

console.log(newObject);

使用 forEach 的相同逻辑

const object = {
  weight: ["0|5"],
  species: ["human|alien"],
  colour: [
    "Blue-Green|Red|Black|Orange With Green, Red, Yellow And Blue Play Of Colour",
  ],
  shape: ["Rough"],
  uniqueId: "kobe",
};

const newObject = {};


Object.keys(object).forEach(key => {
  const property = object[key];
  //Check if element is an Array
  if (Array.isArray(property)) {
    //Split the first element
    newObject[key] = property[0].split("|");
  } else {
    newObject[key] = property;
  }
})

console.log(newObject);

如果您有混合数组 species: ["human|alien","another","klingon|ferengi"],则接受的答案将无效。试试这个(使用 array.concat()

const objectValues = {
        weight: ["0|5"],
        species: ["human|alien","another","klingon|ferengi"],
        colour: ["Blue-Green|Red|Black|Orange With Green, Red, Yellow And Blue Play Of Colour"],
        shape: ["Rough"],
        uniqueId: "kobe"
    }
    
    let desiredObject={}
    for(let item in objectValues) {
        if(Array.isArray(objectValues[item])) {
            tmp = []
            objectValues[item].forEach(el => tmp=tmp.concat(el.split("|")));
           desiredObject[item] = tmp
        } else desiredObject[item] = objectValues[item]
    }
    console.log(desiredObject);