JSONArray的排序键

时间:2019-01-04 00:45:56

标签: javascript json

我有一个像这样的json数组:

[
    {
        "pos1": "Batterie de préchauffage",
        "attributes": [
            {
                "disconnect": "false",
                "disconnectBis": "false"
            }
        ]
    },
    {
        "pos4": "Batterie haute température",
        "attributes": [
            {
                "test": "true",
                "testBis": "false"
            }
        ]
    },
    {
        "pos3": "free"
    },
    {
        "pos2": "free"
    }
]

我如何组织json来进行类似的操作:

[
    {
        "pos1": "Batterie de préchauffage",
        "attributes": [
            {
                "disconnect": "false",
                "disconnectBis": "false"
            }
        ]
    },
    {
        "pos2": "Batterie haute température",
        "attributes": [
            {
                "test": "true",
                "testBis": "false"
            }
        ]
    },
    {
        "pos3": "free"
    },
    {
        "pos4": "free"
    }
]

因为我需要按顺序输入'pos'

我希望有人能理解我的问题,并告诉我该如何解决。.

我已经搜索过,没有发现与我相同的问题。 非常感谢

5 个答案:

答案 0 :(得分:0)

假设对象的第一个属性就是您要排序的对象,那么应该可以简化如下工作:

var array = [
    {
        "pos1": "Batterie de préchauffage",
        "attributes": [
            {
                "disconnect": "false",
                "disconnectBis": "false"
            }
        ]
    },
    {
        "pos4": "Batterie haute température",
        "attributes": [
            {
                "test": "true",
                "testBis": "false"
            }
        ]
    },
    {
        "pos3": "free"
    },
    {
        "pos2": "free"
    }
];

var sortedArray = array.sort((a, b) => {
    var nameKeyA = Object.keys(a)[0];
    var nameKeyB = Object.keys(b)[0];
    return nameKeyA > nameKeyB;
});

console.log(JSON.stringify(sortedArray));

答案 1 :(得分:0)

聚会晚了一点,但我不认为其他答案会产生您想要的输出,即您想保留当前数组顺序并替换数组中对象的当前pos[num]属性与'pos' + (idx + 1)

const input = [ { "pos1": "Batterie de préchauffage", "attributes": [ { "disconnect": "false", "disconnectBis": "false" } ] }, { "pos4": "Batterie haute température", "attributes": [ { "test": "true", "testBis": "false" } ] }, { "pos3": "free" }, { "pos2": "free" } ]

const output = input.map((o, idx) => {
  const id = Object.keys(o).find(id => /^pos/.test(id));
  if (id !== `pos${idx + 1}`) {
    o[`pos${idx + 1}`] = o[id];
    delete o[id];
  }
  return o;
});

console.log(output)

答案 2 :(得分:0)

这将为您提供所需的输出。它使用以下JS方法/语法:

const json = '[{"pos1":"Batterie de préchauffage","attributes":[{"disconnect":"false","disconnectBis":"false"}]},{"pos4":"Batterie haute température","attributes":[{"test":"true","testBis":"false"}]},{"pos3":"free"},{"pos2":"free"}]';

// Parse the JSON
const arr = JSON.parse(json);

// `map` over the array, grabbing the object and index
const out = arr.map((obj, i) => {

  // Iterate over the keys from each object
  Object.keys(obj).forEach(key => {

    // If a key includes the substring "pos"...
    if (key.includes('pos')) {

      // ...and the new key number doesn't match the current index...
      if (key !== `pos${i + 1}`) {

        // ...copy it to a new key (starting at pos1)...
        obj[`pos${i + 1}`] = obj[key];

        // ...then delete the old key
        delete obj[key];

      }
    }
  });

  // Return the updated object 
  return obj;
});

console.log(out);

答案 3 :(得分:-1)

如果名称始终为pos[num],则可以使用。

let data = [
    {
        "pos1": "Batterie de préchauffage",
        "attributes": [
            {
                "disconnect": "false",
                "disconnectBis": "false"
            }
        ]
    },
    {
        "pos4": "Batterie haute température",
        "attributes": [
            {
                "test": "true",
                "testBis": "false"
            }
        ]
    },
    {
        "pos3": "free"
    },
    {
        "pos2": "free"
    }
];

const sortPredicate = (a, b) => {
  
  let aProp = parseInt(Object.getOwnPropertyNames(a)[0].substring(3));
  let bProp = parseInt(Object.getOwnPropertyNames(b)[0].substring(3));

  return  aProp - bProp;
}

let sortedData = data.sort(sortPredicate);

console.log(sortedData);

答案 4 :(得分:-1)

let x = [
    {
        "pos1": "Batterie de préchauffage",
        "attributes": [
            {
                "disconnect": "false",
                "disconnectBis": "false"
            }
        ]
    },
    {
        "pos4": "Batterie haute température",
        "attributes": [
            {
                "test": "true",
                "testBis": "false"
            }
        ]
    },
    {
        "pos3": "free"
    },
    {
        "pos2": "free"
    }
];

function getPosKey(obj) {
  const firstMatch = Object.keys(obj).find(k => /pos[0-9]+/.test(k));
  return firstMatch;
}

const ordered_keys = x.map(o => getPosKey(o)).sort();
x = x.map((o, idx) => {
  const k = getPosKey(o);
  if(k && ordered_keys[idx] && k !== ordered_keys[idx]) {
    o[ordered_keys[idx]] = JSON.parse(JSON.stringify(o[k]));
    delete o[k];
  }
  return o;
});

console.log(JSON.stringify(x, null, 2));