2017-08-20 63 views
1

我有我的特點配置對象:的Javascript:只挑某些屬性的對象

const features = { 
    "feature1": { 
     "value": 1, 
     "description": "" 
    }, 
    "feature2": { 
     "value": 2, 
     "description": "" 
    } 
} 

如何改造它配備/值格式像

{"feature1": 1, "feature2": 2} 

我的變種低於,但我覺得這是不優雅

let config = {}; 

config = Object.keys(features).map(
    k => config[k] = flags[k]["value"] 
); 

回答

1

您可以使用ES6傳播語法與Object.assign()map()

const features = {"feature1":{"value":1,"description":""},"feature2":{"value":2,"description":""}} 
 

 
var result = Object.assign({}, ...Object.keys(features).map(k => ({[k]: features[k].value}))) 
 
console.log(result)

或者你可以使用Object.keys()reduce()

const features = {"feature1":{"value":1,"description":""},"feature2":{"value":2,"description":""}} 
 

 
var result = Object.keys(features).reduce((r, e) => (r[e] = features[e].value, r), {}) 
 
console.log(result)