![](/img/trans.png)
[英]Is there a way to use variable keys in a JavaScript object literal?
[英]How to make a variable using keys from literal object, javascript
在練習中,我必須創建一個名為“fullAddress”的變量,該變量包含給定文字 object 中除第一個鍵之外的所有內容。
我找到了一種可行的解決方案,但我覺得有更好的方法來做到這一點。 此外,我無法弄清楚如何有效地在變量中的值之間放置空間。
練習表明最終結果應如下所示:
39 Johnson Ave, 布魯克林, NY, 11206
但我的看起來像這樣:
約翰遜大街 39 號布魯克林NY11206
練習中提供的字面量 Object:
const restaurant = {
name: 'Ichiran Ramen',
address: `${Math.floor(Math.random() * 100) + 1} Johnson Ave`,
city: 'Brooklyn',
state: 'NY',
zipcode: '11206',
}
我的解決方案:
let fullAddress = restaurant.address + restaurant.city + restaurant.state + restaurant.zipcode;
給定一個字符串數組,您可以使用values.join(', ')
在值之間干凈地放置逗號。 然后你可以做例如[restaurant.address, restaurant.city, restaurant.state, restaurant.zipcode].join(', ')
。
如果您想對任何 object 更通用地執行此操作,您可以使用Object.values(restaurant).slice(1).join(', ')
來動態獲取第一個和逗號分隔之后的所有值。
不過,在這種情況下,我認為用逗號顯式 append 是最有意義的,因為它是一種地址格式(例如,您可能不希望在 zip 代碼之后有空格),例如restaurant.address + ', ' + restaurant.city +...
關於空格(和逗號),您可以像restaurant.address
一樣使用模板字符串。
const restaurant = { name: 'Ichiran Ramen', address: `${Math.floor(Math.random() * 100) + 1} Johnson Ave`, city: 'Brooklyn', state: 'NY', zipcode: '11206', }; let fullAddress = `${restaurant.address}, ${restaurant.city}, ${restaurant.state}, ${restaurant.zipcode}`; console.log(fullAddress); // 39 Johnson Ave, Brooklyn, NY, 11206
接下來,請注意我們實際上使用相同的分隔符連接所有地址部分: ', '
。 這意味着我們可以使用[].join()
代替。
const restaurant = { name: 'Ichiran Ramen', address: `${Math.floor(Math.random() * 100) + 1} Johnson Ave`, city: 'Brooklyn', state: 'NY', zipcode: '11206', }; let addressParts = [restaurant.address, restaurant.city, restaurant.state, restaurant.zipcode]; let fullAddress = addressParts.join(', '); console.log(fullAddress); // 39 Johnson Ave, Brooklyn, NY, 11206
最后,(如果你想變得花哨),請注意那restaurant.
重復。 這可以通過[].map()
避免。
const restaurant = { name: 'Ichiran Ramen', address: `${Math.floor(Math.random() * 100) + 1} Johnson Ave`, city: 'Brooklyn', state: 'NY', zipcode: '11206', }; let fullAddress = ['address', 'city', 'state', 'zipcode'].map(key => restaurant[key]).join(', '); console.log(fullAddress); // 39 Johnson Ave, Brooklyn, NY, 11206
您可以從餐廳 object 中取出所有值,刪除第一個元素然后使用 join 得到所需的字符串
const restaurant = { name: 'Ichiran Ramen', address: `${Math.floor(Math.random() * 100) + 1} Johnson Ave`, city: 'Brooklyn', state: 'NY', zipcode: '11206', } const fullAddress = Object.values(restaurant).slice(1).join(', '); console.log(fullAddress);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.