![](/img/trans.png)
[英]JavaScript - How to extract strings - keys/values from response using RegEx?
[英]Extract keys and values from object via an array of strings in javascript
我有一些作為對象返回的 api 數據:
{
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male"
}
我有一個配置數組中的鍵列表,我有興趣從原始響應中提取:
let attributes = ['name', 'height', 'mass'];
我如何使用屬性數組給我一個對象,如下所示:
{
"name": "Luke Skywalker",
"height": "172",
"mass": "77"
}
您可以循環遍歷您的數組:
const obj = { "name": "Luke Skywalker", "height": "172", "mass": "77", "hair_color": "blond", "skin_color": "fair", "eye_color": "blue", "birth_year": "19BBY", "gender": "male" }; let attributes = ['name', 'height', 'mass']; function buildObject(arr, obj) { const res = {}; arr.forEach(item => res[item] = obj[item]) return res } console.log(buildObject(attributes, obj))
使用reduce
將被簡化。
const update = (data, attrs) => attrs.reduce((acc, attr) => (acc[attr] = data[attr], acc), {}); const data = { name: "Luke Skywalker", height: "172", mass: "77", hair_color: "blond", skin_color: "fair", eye_color: "blue", birth_year: "19BBY", gender: "male" }; let attributes = ["name", "height", "mass"]; console.log(update(data, attributes));
您可以使用Object.entries
方法。
let obj = { "name": "Luke Skywalker", "height": "172", "mass": "77", "hair_color": "blond", "skin_color": "fair", "eye_color": "blue", "birth_year": "19BBY", "gender": "male" }; let attributes = ['name', 'height', 'mass']; let picked = Object.fromEntries( attributes.map(att => [att, obj[att]]) ) console.log(picked);
您可以使用函數reduce
來構建所需的對象。
let obj = {"name": "Luke Skywalker","height": "172","mass": "77","hair_color": "blond","skin_color": "fair","eye_color": "blue","birth_year": "19BBY","gender": "male"}, attributes = ['name', 'height', 'mass'], {result} = attributes.reduce((a, c) => (Object.assign(a.result, {[c]: a.source[c]}), a), {result: Object.create(null), source: obj}); console.log(result);
您可以將想要的鍵與其值一起映射,並使用Object.fromEntries
從中構建一個新對象。
let obj = { name: "Luke Skywalker", height: "172", mass: "77", hair_color: "blond", skin_color: "fair", eye_color: "blue", birth_year: "19BBY", gender: "male" }, attributes = ['name', 'height', 'mass'], picked = Object.fromEntries(attributes.map(k => [k, obj[k]])); console.log(picked);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.