gpt4 book ai didi

javascript - 显示 ng-repeat 中的嵌套对象键和值

转载 作者:行者123 更新时间:2023-12-03 07:27:33 24 4
gpt4 key购买 nike

我有以下数组:

var myArray = [
{"cartItems": {"paramA1": 25, "paramA2": 35}},
{"cartShippingCost": {"paramB1": 4, "paramB2": 152, "paramB3": 536, "paramB4": 56}},
{"cartSpecialRequirements": {"paramC1": 432}},
{"cartPostage": {"paramD1": 56, "paramD2": 6537}},
{"uid": {"paramE1": 545}},
{"tel": 7778798548}
];

然后,我将上面的 if 'cart' 分组到对象键中:

var cartItems = myArray.filter(hasCartProperty);
var nonCartItems = myArray .filter(function (x) {
return !hasCartProperty(x);
});


function hasCartProperty(x) {
return Object.keys(x).some(function (x) {
return x.indexOf('cart') > -1;
});
}

if(Object.keys(cartItems).length > 0) {
cartItems.title = "Shopping Cart Items:";
}
if(Object.keys(nonCartItems).length > 0) {
nonCartItems.title = "Non Cart Items:";
}


$scope.data = [cartItems, nonCartItems];

然后我执行 ng-repeat:

<div x-ng-repeat="myItem in data">
<p>{{myItem.title}}</p>
<p x-ng-repeat="(key, value) in myItem">
{{value}}
</p>
</div>

显示为:

Shopping Cart Items:
{"cartItems": {"paramA1": 25, "paramA2": 35}}
{"cartShippingCost": {"paramB1": 4, "paramB2": 152, "paramB3": 536, "paramB4": 56}}
{"cartSpecialRequirements": {"paramC1": 432}}
{"cartPostage": {"paramD1": 56, "paramD2": 6537}}


Non Cart Items:
{"uid": {"paramE1": 545}}

我如何显示为:

Shopping Cart Items:

cartItems:
{"paramA1": 25,
"paramA2": 35}

cartShippingCost":
{"paramB1": 4, "paramB2": 152,
"paramB3": 536, "paramB4": 56}

cartSpecialRequirements:
{"paramC1": 432}

cartPostage:
{"paramD1": 56,
"paramD2": 6537}


Non Cart Items:

uid:
{"paramE1": 545}

tel:
{7778798548}

最佳答案

使用预标记和自定义格式函数formatValue():

<div x-ng-repeat="myItem in data">
<p>{{myItem.title}}</p>
<pre x-ng-repeat="(key, value) in myItem">{{formatValue(value)}}</pre>
</div>

..

 $scope.formatValue = function(val) {
var firstProp = Object.keys(val)[0];
return firstProp + ":\r\n" + $filter("json")(val[firstProp]);
};

不要忘记将 $filter 添加到 Controller 依赖项中:

.controller("defaultCtrl", function ($scope, $filter) {

结果:

enter image description here

关于javascript - 显示 ng-repeat 中的嵌套对象键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35938167/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com