如何在javascript中将对象放入属性值匹配的数组中。
我有对象a is [1 2 3 4 5]
b is [1 2 3 6 7 8]
和obj1
,如果属性obj2
匹配,在其中
然后推送对象name
的属性,如何在javascript中实现
obj2
预期输出:
function arrayobj(obj1, obj2){
var obj = obj2.map(e=>({
info: {
id: e.id,
qty: e.qty
}
}));
}
var obj1 = [
{
idx:1,
name: "sample1"
},
{
idx:2,
name: "sample2"
}
]
var obj2=[
{
id:1,
name: "sample1",
qty: 10
},
{
id:3,
name: "sample1",
qty: 30
},
{
id:2,
name: "sample2",
qty: 20
}
]
答案 0 :(得分:0)
for(o1 of obj1)
for(o2 of obj2)
if(o1.name==o2.name) {
if(!o1.info) o1.info=[];
o1.info.push({id:o2.id, qty:o2.qty});
}
要查看所获得的内容,请使用:
JSON.stringify(obj1,null," ")
[
{
"idx": 1,
"name": "sample1",
"info": [
{
"id": 1,
"qty": 10
},
{
"id": 3,
"qty": 30
}
]
},
{
"idx": 2,
"name": "sample2",
"info": [
{
"id": 2,
"qty": 20
}
]
}
]
答案 1 :(得分:0)
您需要使用数组的map
和filter
功能才能获得预期的结果。
var obj1 = [
{
idx: 1,
name: "sample1"
},
{
idx: 2,
name: "sample2"
}
]
var obj2 = [
{
id: 1,
name: "sample1",
qty: 10
},
{
id: 3,
name: "sample1",
qty: 30
},
{
id: 2,
name: "sample2",
qty: 20
}
]
const finalArray = obj1.map(obj1Item => {
return {
...obj1Item,
info: obj2
.filter(obj2Item => obj2Item.name === obj1Item.name)
.map(obj2Item => ({ id: obj2Item.id, qty: obj2Item.qty }))
}
})
console.log(finalArray);
答案 2 :(得分:0)
将数组转换为对象以避免内部循环。
function arrayobj(obj1, obj2){
// converting obj2 to object
// with key-> name and value-> array of object{id, qty}
const objFromArray = obj2.reduce((acc, item) => {
if(!acc[item.name]) {
acc[item.name] = [];
}
acc[item.name].push({
id: item.id,
qty: item.qty
});
return acc;
}, {});
// now iterate over the obj1
const result = obj1.map(item => {
return {
...item,
info: objFromArray[item.name]
}
});
return result;
}
var obj1 = [
{
idx:1,
name: "sample1"
},
{
idx:2,
name: "sample2"
}
]
var obj2=[
{
id:1,
name: "sample1",
qty: 10
},
{
id:3,
name: "sample1",
qty: 30
},
{
id:2,
name: "sample2",
qty: 20
}
]
console.log(arrayobj(obj1, obj2));
答案 3 :(得分:0)
这是我的解决方案:
$(document).ready(function () {
// vars
let clonerGroupParent = $('.cloner-group-parent');
let btnAdd = $('.cloner-btn-add');
let btnDel = $('.cloner-btn-del');
let selOptions = {
placeholder: 'Select a station',
allowClear : true
};
// day select2
let selectEle = $('.select2');
// select2 for role
selectEle.select2(selOptions);
//add button click
btnAdd.on('click', function (event) {
// prevent jump
event.preventDefault();
// destroy each select2
selectEle.each(function () {
$(this).select2('destroy');
})
// clone group
clonerGroupParent.children('.cloner-group').last().clone(true, true).appendTo('.cloner-group-parent');
// init each select2
clonerGroupParent.children('.cloner-group').find('.select2').each(function () {
$(this).select2(selOptions);
});
});
});