将对象存储在javascript数组中

时间:2019-02-03 11:16:06

标签: javascript arrays object

我要存储在数组中的对象obj中没有几个对象。在这种情况下,我正在实现push(),但它没有给出正确的输出。有人可以建议实现相同方法的方法。

var obj ={
car:{
maruti: {wheels: 4, mileage:15},
dezire: {wheels: 4, mileage:19}
    },

bike:{
suzuki:{wheels: 2, mileage:45},
honda:{wheels: 2, mileage:85}
     } 
         }

预期输出:

var obj ={
car:[{
maruti: {wheels: 4, mileage:15},
dezire: {wheels: 4, mileage:19}
    }],

bike:[{
suzuki:{wheels: 2, mileage:45},
honda:{wheels: 2, mileage:85}
     } 
         }]

3 个答案:

答案 0 :(得分:2)

您可以将对象的键简化为具有数组中值的对象,如下所示:

const obj = {car:{maruti:{wheels:4,mileage:15},dezire:{wheels:4,mileage:19}},bike:{suzuki:{wheels:2,mileage:45},honda:{wheels:2,mileage:85}}},

res = Object.keys(obj).reduce((acc, key) => ({...acc, [key]:[obj[key]]}), {});
console.log(res);

但是,请注意,对象没有存储保证的顺序,因此生成的对象可能与您输入的顺序不同。

答案 1 :(得分:0)

只需要将[]的每个值放在obj周围。

var obj ={
car:{
    maruti: {wheels: 4, mileage:15},
     dezire: {wheels: 4, mileage:19}
},

bike:{
  suzuki:{wheels: 2, mileage:45},
  honda:{wheels: 2, mileage:85}
     } 
}
for(let key in obj){
	obj[key] = [obj[key]]
}
console.log(obj)

答案 2 :(得分:0)

像这样简单地使用Object.keys()

 

var obj ={
car:{
maruti: {wheels: 4, mileage:15},
dezire: {wheels: 4, mileage:19}
},

bike:{
suzuki:{wheels: 2, mileage:45},
honda:{wheels: 2, mileage:85}
 } 
     }

Object.keys(obj).forEach(key => obj[key] = [obj[key]]);

console.log(obj);
 

对于按里程对车辆进行排序:

 

var obj ={
car:{
maruti: {wheels: 4, mileage:15},
dezire: {wheels: 4, mileage:19}
},

bike:{
suzuki:{wheels: 2, mileage:45},
honda:{wheels: 2, mileage:85}
 } 
     }

Object.keys(obj).forEach(key => obj[key] = [obj[key]]);

Object.keys(obj).forEach(key => obj[key].sort((a, b) => a.mileage - b.mileage));

console.log(obj);