如何在 javascript 中按键值类型更改嵌套对象数组

How to change the nested object array by key value type in javascript

我想知道如何修改 javascript 中的对象数组。

即对于 obj,当 value 是数组

时,将 value 键数组更改为字符串

value 为字符串时,将 value 键字符串更改为数组

此外,如何将输出转换为输入 obj 和(反之亦然-<输入为输出)在 javascript

function newObject(obj){
  var result = obj.map(e=>typeof e.value === "string" ?
  {...e, value: [e.value] } :
   e.value.map(value => ({...e,value})) 
  ).flat()
  console.log(result);
  return result;

}


场景 1

input:
obj =[
 { id: 0, key: "s1", value: ["listA","listB"], img:"" },
 { id: 1, key: "s2", value: ["listC"], img: "" },
 { id: 2, key: "s3", value: ["listD","listE","listF"], img: "" }
]

Expected output:
[
  { id: 0, key: "s1", value: "listA,listB", img:""},
  { id: 1, key: "s2", value: "listC", img:""},
  { id: 2, key: "s3", value: "listD,listE,listF", img:""}
]

场景 2

input
[
  { id: 0, key: "s1", value: "listA,listB", img:""},
  { id: 1, key: "s2", value: "listC", img:""},
  { id: 2, key: "s3", value: "listD,listE,listF", img:""}
]

Expected Output
[
 { id: 0, key: "s1", value: ["listA","listB"], img:"" },
 { id: 1, key: "s2", value: ["listC"], img: "" },
 { id: 2, key: "s3", value: ["listD","listE","listF"], img: "" }
]

当你在逗号上使用.map() you can return a new object with all the properties and values of the current object (...o), along with an update value property. The update value property will check if o.value is an array (checked using Array.isArray), if it is, it will .join() the elements into a string, it is a string (ie: not an array), it will .split()将字符串转换为数组时。

参见下面的示例:

function newObject(arr){
  return arr.map(o => ({
    ...o,
    value: Array.isArray(o.value) ? o.value.join() : o.value.split(',')
  }));
}

const arr1 = [ { id: 0, key: "s1", value: ["listA","listB"], img:"" }, { id: 1, key: "s2", value: ["listC"], img: "" }, { id: 2, key: "s3", value: ["listD","listE","listF"], img: "" } ];
const arr2 = [ { id: 0, key: "s1", value: "listA,listB", img:""}, { id: 1, key: "s2", value: "listC", img:""}, { id: 2, key: "s3", value: "listD,listE,listF", img:""} ];

const res1 = newObject(arr1);
const res2 = newObject(arr2);
console.log(res1);
console.log(res2);

我们可以使用 for 循环来获得更高的性能

let arr_1 = [
  { id: 0, key: "s1", value: ["listA","listB"], img:"" },
  { id: 1, key: "s2", value: ["listC"], img: "" },
  { id: 2, key: "s3", value: ["listD","listE","listF"], img: "" },

  { id: 0, key: "s1", value: "listA,listB", img:""},
  { id: 1, key: "s2", value: "listC", img:""},
  { id: 2, key: "s3", value: "listD,listE,listF", img:""}
]


const f = (arr) => {
  for(let i = 0; i < arr.length; i++) {
    let x = arr[i].value        
    arr[i].value = Array.isArray(x) ? x.join() : x.split(',')
  }
console.log(arr)
}

f(arr_1)