[英]Loop through an array of nested objects in javascript
您可以遍历数组中每个 object 的值,从它们中的每一个创建列表项,然后将它们 append 到列表元素。
let obj = { edges: [ {name: 'Bath', path: '/bath/', entityId: 18}, {name: 'Shop App', path: '/shop-all/', entityId: 23} ] } let ul = document.createElement('ul'); for(const x of obj.edges) for(const textContent of Object.values(x)) ul.append(Object.assign(document.createElement('li'), {textContent})); document.body.append(ul);
目前我能想到的解决方案有两种。
如果您想记录数组的各个元素,此解决方案是最好的。
有一种更好的方法可以更改数组元素,但让我们看一下示例。
const arr = [{ name: "Home", path: "/home" }, { name: "Forums", path: "/forums" }];
arr.forEach((value) => {
console.log(value);
});
// { name: "Home", path: "/home" }
// { name: "Forums", path: "/forums" }
// You can map it to a new value by doing this
const newArr = [];
arr.forEach((value) => {
newArr.push(value.name);
});
console.log(newArr);
// ["Home", "Forums"]
这是我会使用的最佳解决方案。
此方法将单个元素的值更改为 function 中返回的值。
const arr = [{ name: "Home", path: "/home" }, { name: "Forums", path: "/forums" }];
const newArr = arr.map((value) => value.name);
console.log(newArr);
// ["Home", "Forums"]
// Notice how the value has changed
这是解决方案的样子
function YourComponent() {
const edges = product.categories.edges;
const products = edges.map((value) => [value.name, value.path, value.entityId.toString()]);
return (
{
products.map((data) => {
return (
<li>data[0]</li>
<li>data[1]</li>
<li>data[2]</li>
);
});
}
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.