1

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

4 Answers 4

3
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"]
                  };
              });
Sign up to request clarification or add additional context in comments.

Comments

1

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]; });

Comments

1

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);

Comments

0
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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.