1

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"]

sen
  • 91
  • 7

5 Answers5

1

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"]
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

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)
Bunny
  • 536
  • 6
  • 18
0

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 objs are created in different places, the order of the values may not always be the same.

Kobi
  • 135,331
  • 41
  • 252
  • 292
0

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])
polo-language
  • 826
  • 5
  • 13
-1
    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);
  • The question is trying to get an array that looks like this: `["Sen", "SG", "saving", "1233"]` - your code doesn't really help with that - it just prints the results of build-in functions. – Kobi Dec 30 '21 at 12:17