JSON 数据的重新排序

问题描述

我是 JSON 的新手,想重新构建我的 JSON 响应,

JSON 结构现在-

{
    "map": {
    "Cityname": "[Jammu,Srinagar]","Pincode": "[180001,190001]"
     }
}

我需要它如何-

[
  { Cityname: "Jammu",Pincode: 180001},{ Cityname: "Srinagar",Pincode: 190001}
] 

有没有办法做到这一点,我搜索了一些可能的解决方案,但无法做到。

解决方法

您的 JSON 响应,它不太合乎逻辑,因为城市和密码之间没有映射。我假设 cityname 和 pincode 在数组中的顺序相同。 我使用了您在问题中提供的确切 json 结构。

如果您的 json 数据具有正确的数据类型(Cityname 字符串数组/Pincode int 数组),您可以跳过额外的步骤 substring 和解析。

const json = {
    "map": {
    "Cityname": "[Jammu,Srinagar]","Pincode": "[180001,190001]"
     }
}

const someFunc = () => {
    let output = [];
  const {Cityname,Pincode} = json.map;
  const citynameArray = (Cityname.substring(1,Cityname.length-1)).split(",");
  const pincodeArray =  JSON.parse(Pincode);
  
    citynameArray.map((v,i) => {
    output.push({Cityname: v,Pincode: pincodeArray[i]})
  });
  return output;
}

console.log(someFunc());

,

这是一种动态方式,应该可以处理任何具有相同布局的 json 字符串。我修复了你的一些 json 字符串。

// first we use JSON.parse() to turn a json string into a JS Object.
const data = JSON.parse(`{ "map": { "cityName": ["Jammu","Srinagar"],"pinCode": [180001,190001]}}`);

// cities will hold our city objects
const cities = [];

// Object.entries(theObject) returns theObjects keys and values as an array
// EG:
// [[key,value],[key,value]]

// forEach() loops through each key,value pair.
// Because we know that we are going to get a key value pair,// I destructured the array into it's key and values using:
// [key,values] = [properties];

Object.entries(data.map).forEach((prop) => {
  const [key,values] = prop;
  values.forEach((value,index) => {
    // now we check that the current index is an object.
    // we do this because we can't add a property and value otherwise.
    if(typeof cities[index] != "object"){
      cities[index] = {};
    }
    // now we set the current value
    cities[index][key] = value;
  })
})

console.log(cities);