how to restructure a array of arrays into a array of objects

66 views Asked by At

i need help with structuring a new json array of objects. I am starting with a array of arrays. I need to end up with a array of objects. javascript or linq.js will work perfectly. thanks

this is what I am starting with

var needtoChangeThisArray = [
        [1558, 219561],
        [2520, 438218],
        [3482, 656874],
        [4444, 875531],
        [5406, 1094187]
];

this is how the array needs to be structured

var needsToLookLikeThisArray = [
{
"name": "Arbor Vista - Arbor Custom Homes",
"subId": "10394",
"bldId": "8598"
}, {
"name": "Arbor Vista - DR Horton - (OR)",
"subId": "10394", "bldId": "8597"
}, {
"name": "Copper Canyon Estates - Brentwood Homes",
"subId": "9048",
"bldId": "16737"
}`enter code here`
];

So I need to end up with this

var needToEndUpWithThisArray = [
{
"sqft": "1558",
"price": "219561"
}, {
"sqft": "2520",
"price": "438218"
}, {
"sqft": "3482",
"price": "656874"
 }, {
"sqft": "4444",
"price": "875531"
}, {
"sqft": "5406",
"price": "1094187"
}
];
2

There are 2 answers

0
Tesseract On BEST ANSWER

Is this sufficient?

needToEndUpWithThisArray = needtoChangeThisArray.map(function(a) {
  return {
    sqft: a[0],
    price: a[1]
  };
});
0
Niddro On

This should do it:

//Your starting array
var needtoChangeThisArray = [
        [1558, 219561],
        [2520, 438218],
        [3482, 656874],
        [4444, 875531],
        [5406, 1094187]
];

//declaring your new array
var needToEndUpWithThisArray = new Array();

//looping through all your values, could also go with ForEach
for (var i = 0; i < needtoChangeThisArray.length; i++) {
    var t = needtoChangeThisArray[i];
    var tempArray = {sqft:t[0], price:t[1]};
    needToEndUpWithThisArray.push(tempArray); //stuff your new array with the values.
}