我有2个不同的对象数组,我想根据“id”值合并。
所以如果我的第一个数组看起来像这样:
Sub searchfilter(ByVal mytextbox As TextBox, ByVal myfield As String)
If Not source1.DataSource = ExcelDB.DataSource Then
source1.DataSource = ExcelDB.DataSource
End If
ExcelDB.DataSource = source1
Dim searchstring As String = ""
If mytextbox.Text = "" Then
source1.RemoveFilter()
Else
source1.Filter = myfield & " = '" & mytextbox.Text & "'"
addquery(myfield & "= '" & mytextbox.Text & "'")
End If
End Sub
我的第二个看起来像这样:
[
{
"id": "75318408571184",
"component": "textInput",
"index": 0,
"label": "Text",
"description": "description",
"placeholder": "placeholder",
},
{
"id": "9463537670672",
"component": "textArea",
"index": 1,
"label": "Paragraph",
"description": "description",
"placeholder": "placeholder"
}
我想得到这个对象数组:
[
{
"id": "75318408571184",
"value": "value1"
},
{
"id": "9463537670672",
"value": "value2"
}
有没有一种巧妙的方法可以在角度或javascript中执行此操作而不循环遍历数组?
答案 0 :(得分:2)
试试这个:
var result = firstArray.map(function(item) {
var second = secondArray.find(function(i) {
return item.id === i.id;
});
return second ? Object.assign(item, second) : item;
});
console.log(result);
Array.prototype.map()在firstArray
的每个项目的参数中应用函数,并返回带有修改值的新数组。
Object.assign()是一个函数,它将second
对象的属性复制到上面代码中的item
对象。
答案 1 :(得分:2)
在普通的Javascript中,您可以使用Array.prototype.forEach()
和Array.prototype.some()
var obj1 = [{ "id": "75318408571184", "component": "textInput", "index": 0, "label": "Text", "description": "description", "placeholder": "placeholder", }, { "id": "9463537670672", "component": "textArea", "index": 1, "label": "Paragraph", "description": "description", "placeholder": "placeholder" }],
obj2 = [{ "id": "75318408571184", "value": "value1" }, { "id": "9463537670672", "value": "value2" }];
obj2.forEach(function (a) {
obj1.some(function (b) {
if (a.id === b.id) {
b.value = a.value;
return true;
}
});
});
document.write('<pre>' + JSON.stringify(obj1, 0, 4) + '</pre>');
另一种可能性是首先构建哈希表temp
,然后直接操作该项。
var obj1 = [{ "id": "75318408571184", "component": "textInput", "index": 0, "label": "Text", "description": "description", "placeholder": "placeholder", }, { "id": "9463537670672", "component": "textArea", "index": 1, "label": "Paragraph", "description": "description", "placeholder": "placeholder" }],
obj2 = [{ "id": "75318408571184", "value": "value1" }, { "id": "9463537670672", "value": "value2" }],
temp = {};
obj1.forEach(function (a, i) {
temp[a.id] = i;
});
obj2.forEach(function (a) {
obj1[temp[a.id]].value = a.value;
});
document.write('<pre>' + JSON.stringify(obj1, 0, 4) + '</pre>');
答案 2 :(得分:2)
以上答案已经很好了。但是如果你想看看其他一些库,你可以看看这个。 loadash merge
var object = {
'fruits': ['apple'],
'vegetables': ['beet']
};
var other = {
'fruits': ['banana'],
'vegetables': ['carrot']
};
_.merge(object, other, function(a, b) {
if (_.isArray(a)) {
return a.concat(b);
}
});
// → { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }