Home > Software design >  JSON Array convert to array of objects
JSON Array convert to array of objects

Time:08-27

I have problem with JSON object. How do I convert an array:

[["age"],[12],[34],[53],[18],[32]] 

to an array of object:

[{"age": 12},{"age":34},{"age":53},{"age":18},{"age":32}]. 

CodePudding user response:

This would solve your problem (in JS, same logic should work on c#), having that the first array item is the key of the others:

var source = [["age"],[12],[34],[53],[18],[32]];
function convertToObjectArray(arr){
    var objArr = [];
    var prop = arr[0];
    for(var i = 1; i<arr.length;i  ){
        objArr.push({[prop]: arr[i][0]});
    }
    return objArr;
}
console.log(convertToObjectArray(source));

CodePudding user response:

try this

using Newtonsoft.Json;

var json = "[[\"age\",\"sex\"],[12,0],[18,1],[44,0],[56,1]]";

    var jArr = JArray.Parse(json);
    var newJArr = new JArray();
    for (var i = 1; i < jArr.Count; i  )
    {
        var jObj = new JObject();

        for (var j = 0; j < jArr[0].Count(); j  )
            jObj.Add((string)jArr[0][j], jArr[i][j]);

        newJArr.Add(jObj);
    }
    json=newJArr.ToString();

newJArr

[
  {
    "age": 12,
    "sex": 0
  },
  {
    "age": 18,
    "sex": 1
  },
  {
    "age": 44,
    "sex": 0
  },
  {
    "age": 56,
    "sex": 1
  }
]

CodePudding user response:

I'm not sure why you have an array that has both strings and numbers in it, but I think I can at least get you on the right track. Before trying the code below, remove "age" from your original array. Then use the reduce function.

const oldArr = [[12],[34],[53],[18],[32]];
const newObj = oldArr.reduce((arr, x) => arr.concat({"age":x[0]}), [])

Run the code above and console log newObj.

  • Related