如何将JSON数组更改为其他格式

时间:2017-06-08 10:42:49

标签: javascript arrays json

数组有对象。示例如下;

  [{
    "Id": 1,
    "ParentId": -1,
    "Name": "Mobilya",
    "Slug": "",
    "Content": "",
    "Icon": "",
    "Code": "",
    "Order": 1,
    "IsShowing": true
  },
  {
    "Id": 2,
    "ParentId": -1,
    "Name": "Televizyon",
    "Slug": "",
    "Content": "",
    "Icon": "",
    "Code": "",
    "Order": 2,
    "IsShowing": true
  },
  {
    "Id": 16,
    "ParentId": 1,
    "Name": "Köşe Takımları",
    "Slug": "",
    "Content": "",
    "Icon": "",
    "Code": "",
    "Order": 5,
    "IsShowing": true
  }]

我想将其更改为

  [{
    "id": 1,
    "label": "Mobilya",
    "clickableId": "ndMainCategory",
    "icon": "",
    "items": [{
              "id": 16,
              "label": "Köşe Takımları"
              }]
   },
   {
    "id": 2,
    "label": "Mobilya",
    "clickableId": "ndMainCategory",
    "icon": ""
   }]

如果ParentId为-1,则表示它是主category.clickableId":"ndMainCategory",这对于每个主要类别都是静态的。     第一个数组来自api,我必须将它改为另一个,但我无法做到。我怎么能这样做。

由于

提前;

3 个答案:

答案 0 :(得分:0)

这就是你读json的方式。

var text = '[{"description":"about_text","value1":"test1","value2":"test2"}]';

obj = JSON.parse(text);
var yourvar_description = obj[0].description;
var yourvar_value1 = obj[0].value1 ;
var yourvar_value2 = obj[0].value2 ;

所以,如果我想要的话     var text ='[{“description”:[{“value1”:“test1”,“value1”:“test2”}]}];

var newJson = "[{ description : [{ value1 :"+yourvar_value1+", value2:"+yourvar_value2+" ...etc"

我相信你明白了。

正如@charlietfl所解释的,这不是一个免费的代码编写服务。 Objetive是帮助您改进代码,但为此您必须发布一些代码。

答案 1 :(得分:0)

我认为这就是你要找的东西

console.log(changeList([{"Id": 1,"ParentId": -1,"Name": "Mobilya","Slug": "","Content": "","Icon": "","Code": "","Order": 1,"IsShowing": true},{"Id": 2,"ParentId": -1,"Name": "Televizyon","Slug": "","Content": "","Icon": "","Code": "","Order": 2,"IsShowing": true},{"Id": 16,"ParentId": 1,"Name": "Köşe Takımları","Slug": "","Content": "","Icon": "","Code": "","Order": 5,"IsShowing": true}]));

/**
 * @param {string|Array<object>} input 
 * @returns {string|Array<object>}
 */
function changeList(input) {
  // Below lines check if input is in string or array form
  var isList = input instanceof Array;
  var list = isList ? input : JSON.parse(String(input));

  // The list that stores all the items
  var result = {}; 

  // Returns an empty JSON list if input is invalid
  if (!(list instanceof Array)) return "[]";

  // Loop for all the items in the list
  for (var index = 0; index < list.length; index++) {
    var item = list[index]; // the item
    var id = item["Id"]; // item id
    var parentId = item["ParentId"]; // item parent id

    // if the parent Id is not -1 and there is an item in the list with that id
    if (parentId !== -1 && result.hasOwnProperty(parentId)) {
      
      var parent = result[parentId]; // get the parent
      // get parent's item or if it doesn't have any instantiate a new array
      var items = parent["items"] || [];
      // add the item to the list
      items.push({
        "id": id,
        "label": item["Name"]
      });
      // add the array to the parent
      parent["items"] = items;

    } else if(!result.hasOwnProperty(id)){

      // if it doesn't have a parent and it doesn't already exist in the list, create it and add it

      result[id] = {
        "id": id,
        "label": item["Name"],
        "clickableId": "ndMainCategory",
        "icon": item["Icon"]
      };
    }
  }
  // Finally convert the object into a list and return it in the form it was entered
  var resultList = Object.values(result);
  return isList ? resultList : JSON.stringify(resultList);
}

答案 2 :(得分:0)

您可以使用递归的reduce()方法创建将返回此结果的函数。

var data = [{"Id":1,"ParentId":-1,"Name":"Mobilya","Slug":"","Content":"","Icon":"","Code":"","Order":1,"IsShowing":true},{"Id":2,"ParentId":-1,"Name":"Televizyon","Slug":"","Content":"","Icon":"","Code":"","Order":2,"IsShowing":true},{"Id":16,"ParentId":1,"Name":"Köşe Takımları","Slug":"","Content":"","Icon":"","Code":"","Order":5,"IsShowing":true}]

function format(data, pid) {
  return data.reduce(function(r, e) {
    var obj
    if (pid == -1) obj = {id: e.Id,label: e.Name,clickableId: "ndMainCategory",icon: e.Icon}
    else obj = {id: e.Id,label: e.Name}

    if (e.ParentId == pid) {
      var children = format(data, e.Id)
      if (children.length) obj.items = children
      r.push(obj)
    }

    return r;
  }, [])
}

console.log(format(data, -1))