简体   繁体   中英

Store objects in an array in javascript

I have few Objects in an object obj which I want to store in array.I am implementing push() for this case but it isn't giving correct output. Can someone suggest the approach to implement the same.

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

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

Expected Output:

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

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

You can reduce the object's keys to an object with its value in an array like so:

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

However, do note, objects don't store a guaranteed order, and thus the resulting object may be in a different order to your input.

just you need to put [] around ur each value of 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)

Simply use Object.keys() like so:

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

And for sorting the vehicles by mileage:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM