gpt4 book ai didi

javascript - 如何以逗号分隔获取具有相同键值的对象

转载 作者:行者123 更新时间:2023-11-30 00:06:12 26 4
gpt4 key购买 nike

我有一个对象数组,每个对象都有键和值。我想如果对象有相同的键,那么它们的值应该由相同键的所有值以逗号分隔。我的 html 代码:

<p ng-repeat="item in allOptions" class="item" id="{{item.id}}">
{{item.id}} <input type="checkbox" ng-change="sync(bool, item)" ng-model="bool" > {{item}} Selected: {{bool}}
</p>

我的 Controller 代码是:

 $scope.allOptions = [
{
"id": "1",
"data": "one",
},
{
"id": "1",
"data": "two",
},
{
"id": "2",
"data": "three",
},
];

$scope.data = [

];

$scope.sync = function(bool, item){

if(bool){
// add item
$scope.data.push(item);
} else {
// remove item
for(var i=0 ; i < $scope.data.length; i++) {
if($scope.data[i] == item.id){
$scope.data.splice(i,1);
}
}
}
};

在数据数组中我有对象,如果我们选择相同的对象键(相同的id值)那么我想要

{
"id": "1",
"data": "one","two",
}

最佳答案

var myData = [{
"id": "1",
"data": "one",
},{
"id": "1",
"data": "two",
},{
"id": "2",
"data": "three",
}];

var output = [];

//Iterating each element of the myData
myData.forEach(o => {

//Checking the duplicate value and updating the data field
let temp = output.find(x => {
if (x && x.id === o.id) {
x.data += ", " + o.data;
return true;
}
});
if(!temp)
output.push(o);

});
console.log(output);

关于javascript - 如何以逗号分隔获取具有相同键值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38437510/

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