I would like to know how to get particular key from object and convert to array in javascript
var result = Object.entries(obj).includes(obj.name || obj.country || obj.account || obj.pincode).map(e=>e);
var obj = {
"name" : "Sen",
"country": "SG",
"key" : "Finance",
"city": "my",
"account":"saving",
"pincode":"1233"
}
Expected Output
["Sen", "SG", "saving", "1233"]
CodePudding user response:
Create an array of requested keys
, and then map it and take the values from the original object:
const obj = {"name":"Sen","country":"SG","key":"Finance","city":"my","account":"saving","pincode":"1233"}
const keys = ['name', 'country', 'account', 'pincode']
const result = keys.map(k => obj[k])
console.log(result) // ["Sen", "SG", "saving", "1233"]
CodePudding user response:
I think you can try it like this.
There're other ways to get that result, too. Here's just a simple solution.
var obj = {
"name" : "Sen",
"country": "SG",
"key" : "Finance",
"city": "my",
"account":"saving",
"pincode":"1233"
}
let arrObj = []
let result = arrObj.push(obj.name, obj.country, obj.account, obj.pincode)
console.log(arrObj)
CodePudding user response:
filter
by a Set
containing just the keys you want, then use map
to return just the values:
const keys = new Set(['name', 'country', 'account', 'pincode'])
Object.entries(obj).filter(entry => keys.has(entry[0])).map(entry => entry[1])
CodePudding user response:
If you want an array based on a known, hardcoded list of properties, the easiest option is an array literal:
const result = [obj.name, obj.country, obj.account, obj.pincode];
A benefit of this approach is that it guarantees the order of values in the array. While the order is predictable in your example (one onject literal), f your obj
s are created in different places, the order of the values may not always be the same.
CodePudding user response:
var obj = {
"name" : "Sen",
"country": "SG",
"key" : "Finance",
"city": "my",
"account":"saving",
"pincode":"1233"
}
const Names = Object.keys(obj);
console.log(Names);
const Values = Object.values(obj);
console.log(Values);
const entries = Object.entries(obj);
console.log(entries);