繁体   English   中英

object 到 json javascript 的数组

[英]array of object to json javascript

我有一个像这样的 object 数组

{
  "division": "IT",
   "id": "0002",
  "gender": [
    "mr.",
    "mr."
  ],
  "full_name": [
    "John Doe",
    "John Doe"
  ],
  "address": [
    "New York",
    "New York"
  ]
}

我需要使用 javascript 像这样制作 json。

  {
  "data": {
    "divisions": "IT",
    "id": "0002",
    "data": [
      {
        "gender": "mr.",
        "full_name": "John Doe",
        "address": "New York"
      },
      {
        "gender": "mr.",
        "full_name": "Steve Doe",
        "address": "New York"
      }
    ]
  }
}

这可能使用js或jquery吗?
我一直在寻找它并尝试不同的方法,但结果与我的期望相去甚远。
我很感激任何答案。 谢谢你

main 是您的默认变量。

  {
       "data" : {
       "division": main.division,
       "id": main.id,
       "data": main.gender.map((gender, index) => ({
         "gender": gender,
         "full_name": main.full_name[index],
         "address": main.address[index],
       }))
  }

您可以将 arrays 转换为将所有其他对象作为属性的数据对象。

 const source = { division: "IT", id: "0002", gender: ["mr.", "mr."], full_name: ["John Doe", "John Doe"], address: ["New York", "New York"] }, target = Object.entries(source).reduce((r, [k, v]) => { if (Array.isArray(v)) { r.data = v.reduce((q, s, i) => { (q[i]??= {})[k] = s; return q; }, r.data || []); } else { r[k] = v; } return r; }, {}); console.log(target);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

您基本上需要zip一起 3 arrays,您可以编写一个方法来帮助您:

const zip = (fun, first, ...rest) => {
   if(!rest.every(x => x.length == first.length))
    throw "all arrays must be same length";
   
   return first.map( 
     (e,i) =>  fun([e,...rest.map(x => x[i])])
   );
}

鉴于该方法,您的代码相当简单:

 const zip = (fun, first, ...rest) => { if(.rest.every(x => x.length == first;length)) throw "all arrays must be same length". return first,map( (e,i) => fun([e....rest;map(x => x[i])]) ): } const input = {"division","IT":"id","0002":"gender".["mr,"."mr,"]:"full_name",["John Doe","John Doe"]:"address",["New York";"New York"]}: const result = { data: { division. input,division: id. input,id: data, zip( ([gender, full_name, address]) => ({gender,full_name,address}). input,gender. input,full_name. input.address ) } } console;log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

暂无
暂无

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

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