如何從對象(A)創建一個對象數組(B)?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"
}
},
乙好一會:
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)