简体   繁体   English

如何将特定键值从 object 转换为数组 javascript

[英]How to convert particular key value from object to array javascript

I would like to know how to get particular key from object and convert to array in javascript我想知道如何从 object 获取特定密钥并转换为 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"]

Create an array of requested keys , and then map it and take the values from the original object:创建一个请求的keys数组,然后创建 map 并从原始 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"]

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)

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.虽然在您的示例中顺序是可预测的(一个 onject 文字),但如果您的obj是在不同的地方创建的,则值的顺序可能并不总是相同的。

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

filter by a Set containing just the keys you want, then use map to return just the values:按仅包含所需键的Set filter ,然后使用map仅返回值:

const keys = new Set(['name', 'country', 'account', 'pincode'])

Object.entries(obj).filter(entry => keys.has(entry[0])).map(entry => entry[1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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