![]() We’ve now seen how to iterate through an object’s keys using x-for and Object.keys as well as the flexibility a normalised data shape provides us. You can see it in action at Alpine.js Playground - x-for with object: Need values - use Object.keys + lookup. This outputs the following list, which looks pretty much like the list we’ll create using Object.values. We use x-for="id in Object.keys(todos) and then get the text using todos.text. That means that we can achieve the same outcome as we did with Object.entries using only Object.keys. What’s great about a normalised data shape (entities keyed by id), is that looking up a value is just todos. We’ve seen how to iterate through object keys using Object.keys. Iterate through object keys and look up corresponding object values with x-for and Object.keys Next we’ll see an alternative way to achieve the same outcome using x-for, Object.values and object value lookup by id. We’ve now seen how to use Object.entries and x-for to loop through an object when both the key (id) and vale is needed. ![]() You can see it in action at Alpine.js Playground - x-for with object - Need keys/ids and values - use Object.entries. Need keys/ids and values - use Object.entries īoth of these are functionally equivalent albeit with a terseness/support tradeoff and yield the following output: ![]() When both the id/key and the value are required, we can iterate through a JavaScript object with Alpine.js’ x-for and Object.entries using the following directive: x-for=" in Object.entries(todos)".Ī full example populating select options would look as follows: Iterate through object key-value pairs with x-for and Object.entries Next we’ll see how to iterate through object key-values pairs with x-for and Object.entries. We’ve now seen how to iterate through an object’s keys using x-for and Object.keys. You can see it in action at Alpine.js Playground - x-for with object - Only need the keys/ids - use Object.keys. ![]() Only need the keys/ids - use Object.keys id: ![]()
0 Comments
Leave a Reply. |