2015-09-10 3 views
1

Как создать массив объектов (B) с объекта (A)?Javascript: создать массив объектов из объекта

Я получаю этот объект:

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 Пытаюсь получить:

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

Это то, что я пробовал:

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

ответ

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

Более общий способ извлечения ключей/значений на основе данных без явного ссылаясь на какое-либо конкретное значение строки другой, того число.

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

Plain путь, 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); 
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(); 
Смежные вопросы