[英]How to combine two values of same property in object by using comma separator?
I have scenario to combine the values of same property with seperator. 我有方案结合使用分隔符相同属性的值。 Is it possible. 可能吗。 My json structure is like this: 我的json结构是这样的:
{
"name": "aa",
"name": "bb",
"name1": "cc",
"name2": "dd"
}
I want to display the value of key (name) as aa, bb
. 我想将键(名称)的值显示为aa, bb
。
You can modify the json to get required solution 您可以修改json以获取所需的解决方案
var obj = [
{ key : 'name' , value : 'foo' },
{ key : 'name' , value : 'bar' },
{ key : 'name1', value : 'baz' }
];
values = [];
for (var i = 0; i < obj.length; i++)
{
if (obj[i].key === 'name')
{
values.push(obj[i].value);
}
}
console.log(values.join());
You are using the same key name
in your JSON. 您在JSON中使用相同的键name
。
This does not make sense. 这根本不符合逻辑。 Instead you can try this approach: 相反,您可以尝试这种方法:
Create unique keys in your JSON, like, 在JSON中创建唯一键,例如,
var mockDataForThisTest = "json=" + encodeURI(JSON.stringify([
{
"name":"aa",
"name0":"bb",
"name1":"cc",
"name2":"dd"},
]));
Then you need to load the JSON in a $scope
variable from your controller
然后,您需要从controller
的$scope
变量中加载JSON
function nameCtrl($scope, $http) {
$scope.names= [];
$scope.loadNames = function() {
var httpRequest = $http({
method: 'POST',
url: '/echo/json/',
data: mockDataForThisTest
}).success(function(data, status) {
$scope.names= data;
});
};
}
Then in the html page, 然后在html页面中,
<div ng-repeat="name in names">
{{name.name}}
<span>,</span>
{{name.name0}}
<span>,</span>
{{name.name1}}
<span>,</span>
{{name.name2}}
</div>
Hope it helps! 希望能帮助到你!
Create filter like this 像这样创建过滤器
app.filter('join', function () {
return function join(array, separator, prop) {
if (!Array.isArray(array)) {
return array; // if not array return original - can also throw error
}
return (!!prop ? array.map(function (item) {
return item[prop];
}) : array).join(separator);
};
});
Use in template like this 在这样的模板中使用
<span>{{var1 | var2 | join:', ' }}</span>
Creating filter enables you to use it any times. 创建过滤器使您可以随时使用它。 You will have to just place variables that you want to join by separator in place of var1
and var2
. 您只需要放置要通过分隔符var1
变量来代替var1
和var2
。
Regards. 问候。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.