I am trying to access java script object which is available in the below format:
[
{'To':'A','From':'X','Weight':5},
{'To':'A','From':'Y','Weight':7},
{'To':'A','From':'Z','Weight':6},
{'To':'B','From':'X','Weight':2},
{'To':'B','From':'Y','Weight':9},
{'To':'B','From':'Z','Weight':4}
]
How can I access above object to create array like below ?
[
[ 'A', 'X', 5 ],
[ 'A', 'Y', 7 ],
[ 'A', 'Z', 6 ],
[ 'B', 'X', 2 ],
[ 'B', 'Y', 9 ],
[ 'B', 'Z', 4 ]
]
CodePudding user response:
You can
Use
Array.map()
andObject.values()
:const arrOfArrs = arr.map( Object.values );
Use Lodash's _.map() and _.values() in the same manner:
const _ = require('lodash'); . . . const arrOfArrs = _.map( arr , _.values );
You should, however, be aware that the order in which an object's properties are iterated over (and hence returned) is not guaranteed in any way by the Ecmascript/Javascript standard. It can vary from Javascript implementation to implementation, and can even change from execution to execution. The most common order in which things are returned is insertion order, but that's not guaranteed.
CodePudding user response:
Well, you can use array method .map()
let arr = [
{'To':'A','From':'Y','Weight':7},
{'To':'A','From':'Z','Weight':6}
]
let result = arr.map(Object.values)
console.log(result)
CodePudding user response:
Use a map function:
const l = [
{'To':'A','From':'X','Weight':5},
{'To':'A','From':'Y','Weight':7},
{'To':'A','From':'Z','Weight':6},
{'To':'B','From':'X','Weight':2},
{'To':'B','From':'Y','Weight':9},
{'To':'B','From':'Z','Weight':4}
]
const newArray = l.map(el => [el.To, el.From, el.Weight])
console.log(newArray);
CodePudding user response:
let a = [{'To':'A','From':'X','Weight':5},{'To':'A','From':'Y','Weight':7},{'To':'A','From':'Z','Weight':6},{'To':'B','From':'X','Weight':2},{'To':'B','From':'Y','Weight':9},{'To':'B','From':'Z','Weight':4}]
let array = []
for(i in a){
let temp = [a[i]['To'], a[i]['From'], a[i]['Weight']]
array.push(temp)
}
console.log(array)
CodePudding user response:
You could use this to ensure the correct order of items in inner array.
let arr = [{'To':'A','From':'X','Weight':5},{'To':'A','From':'Y','Weight':7},{'To':'A','From':'Z','Weight':6},{'To':'B','From':'X','Weight':2},{'To':'B','From':'Y','Weight':9},{'To':'B','From':'Z','Weight':4}]
let result = arr.map(obj => [obj.To, obj.From, obj.Weight]);
console.log(result);