Simo Mafuxwana
Simo Mafuxwana

Reputation: 3772

Javascript: Create an array of objects from an Object

How do I create an array of objects (B) from an object (A)?

A I get this object:

var _currentData  = {
    "companyRelationships": {
        "0.company": "company0",
        "0.companyRelationship": "company0 relationship",
        "1.company": "company1",
        "1.companyRelationship": "company1 relationship",
        "2.company": "company2",
        "2.companyRelationship": "company2 relationship"
    }
},

B Trying to get:

companyRelationships: [
    {
        "company": "company0"
        "companyRelationship": "company0 relationship"
    },
    {
        "company": "company1"
        "companyRelationship": "company1 relationship"
    },
    { 
        "company": "company2"
        "companyRelationship": "company2 relationship"
    }
]

This is what I tried:

var _currentData  = {
    "companyRelationships": {
        "0.company": "company0",
        "0.companyRelationship": "company0 relationship",
        "1.company": "company1",
        "1.companyRelationship": "company1 relationship",
        "2.company": "company2",
        "2.companyRelationship": "company2 relationship"
    }
},
bb = {}, 
arrOne = [], 
 arrTwo = [], 
custKey;

    for(b in _currentData) {
        var n = 0; // to know which item to lookup in the array
        for(c in _currentData[b]) {
            custKey = c.substring(0, c.indexOf('.'));

            // using arrOne to check if array item custKey already exists
            // if not then create a new key in bb then assign the value
            if (arrOne.indexOf(custKey) === -1) {
                console.log(arrTwo.indexOf(custKey));
                bb[c.split('.').pop()] = _currentData[b][c];
                arrTwo.push(bb)
                arrOne.push(custKey)
                console.log('objectSet',bb)
            } else {
                // if custKey is an item in arrOne, find its position
                // then update the obj keys
                console.log(arrOne.indexOf(custKey));
                arrTwo[n][c.split('.').pop()] = _currentData[b][c];                        
                //arrTwo.push(bb)
                n++;
            }
        };
    };
    console.log('finalArry',arrTwo)

FIDDLE

Upvotes: 1

Views: 214

Answers (4)

Oliver Fencott
Oliver Fencott

Reputation: 162

let companyRelationships = [];

function populateCompanyRelationshipsArray() {
  Object.getOwnPropertyNames(_currentData.companyRelationships).map(companyRelationshipKey => {
    const index = companyRelationshipKey.slice(0, 1);
    if (companyRelationshipKey.includes('companyRelationship')) {
      companyRelationships.push({
        company: `company${index}`,
        companyRelationship: `company${index} Relationship`
      });
    }
  });
}

populateCompanyRelationshipsArray();

Upvotes: 0

FarazShuja
FarazShuja

Reputation: 2370

Plain way, jsfiddle: http://jsfiddle.net/vc5kgkcc/

var arrayB = [];
var index = 0;
for(b in _currentData.companyRelationships) {

    var val = _currentData.companyRelationships[b];
    var pKey = b.split('.')[1];    
    if(index%2==0) {    
        arrayB.push({});
    }

    arrayB[arrayB.length-1][pKey] = val;

    index++;
}
console.log(arrayB);

Upvotes: 1

Sagi
Sagi

Reputation: 9294

More generic way to extract keys/values based on your data without explicitly referring to any specific value of the string other then the number.

var map = {};

Object.keys(json.companyRelationships).forEach(function(key){
   var num = key.match(/\d+/g, '')[0];
   var mapped = map[num] || (map[num] = {});
   var companyKey = key.replace(/\d\.+/g, '');
   var value = json.companyRelationships[key];

   mapped[companyKey] = value;
});

var result = Object.keys(map).map(function(e){ return map[e]; });

Upvotes: 1

Andreas
Andreas

Reputation: 21911

var companyRelationships =
        // get all companies (keys)
        Object.keys(_currentData.companyRelationships)
              // we're only interested in the keys w/o "Relationship" in it
              .filter(function(key) {
                  return key.indexOf("Relationship") === -1;
              })
              // "iterate" over the keys and return the result object
              .map(function(key) {
                  return {
                      "company": _currentData.companyRelationships[key],
                      "companyRelationship": _currentData.companyRelationships[key + "Relationship"]
                  };
              });

Upvotes: 3

Related Questions