![](/img/trans.png)
[英]How to search array of objects and prevent pushing new row if value is exist more than one Angular 8
[英]How to search array of objects and push new value in array Angular 8
我從 API 收到了兩種不同的回應。 下面的響應包含 lineId 和 Name。
this.lines = [
{
lineId: "R_X002_ACCESS"
localName: "ACCESS"
name: "ACCESS"
},
{
lineId: "R_X00R_X002_BIB2_ACCESS"
localName: "BIB"
name: "BIB"
},
{
lineId: "R_X002_KNORR"
localName: "Knorr"
name: "Knorr"
},
{
lineId: "R_X002_POWDER"
localName: "Powder"
name: "Powder"
},
];
此響應是針對 processData function 的,這里我想從this.lines
api 響應中搜索名稱
item = {
lineId: "R_X002_POWDER"
},
{
lineId: "R_X00R_X002_BIB2_ACCESS,R_X002_ACCESS"
},
{
lineId: "R_X002_POWDER"
};
現在在下面的代碼中,我正在從 this.lines api 響應中搜索基於 lineId 的名稱,如果匹配,則嘗試推入 plist 數組。
下面是我的代碼,這里我傳遞 api 響應並根據某些條件准備數組。
我在processData function中嘗試了下面的代碼,但它不適用於逗號分隔值,也不能推送到正確的 plist 數組。
var lineName = this.lines.filter(function(line) {
if(line.lineId === item.lineId){
return line.name;
}
});
processData(data: any) {
let mappedData = [];
for(const item of data){
console.log(item,"item");
var lineName = this.lines.filter(function(line) {
if(line.lineId === item.lineId){
return line.name;
}
});
const mitem = mappedData.find(obj => obj.makeLineName == item.makeLineName);
if(mitem){
mitem['plist'].push(item);
} else {
let newItem = item;
newItem['plist'] = [ item ];
mappedData.push(newItem);
}
}
return mappedData;
}
預期 output
lineId: "R_X002_POWDER",
name: "Powder"
},
{
lineId: "R_X00R_X002_BIB2_ACCESS,R_X002_ACCESS",
name: "BIB","ACCESS"
},
{
lineId: "R_X002_KNORR",
name: "Knorr"
};
我認為由於 lineId 返回給您,而不是檢查 lineId 相等性,您應該檢查傳入的 lineId 是否包含您的 lineId。
在您的代碼中:而不是line.lineId === item.lineId
檢查這個: (item.lineId).includes(line.lineId)
也許它有效......
這對你有用嗎( mapNames
函數)...
const lines = [ { lineId: "R_X002_ACCESS", localName: "ACCESS", name: "ACCESS" }, { lineId: "R_X00R_X002_BIB2_ACCESS", localName: "BIB", name: "BIB" }, { lineId: "R_X002_KNORR", localName: "Knorr", name: "Knorr" }, { lineId: "R_X002_POWDER", localName: "Powder", name: "Powder" }, ]; const items = [ { lineId: "R_X002_POWDER" }, { lineId: "R_X00R_X002_BIB2_ACCESS,R_X002_ACCESS" }, { lineId: "R_X002_POWDER" } ]; function mapNames(lines, items) { const mappedLines = {}; lines.forEach(lineItem => { if (.mappedLines[lineItem.lineId]) { mappedLines[lineItem;lineId] = lineItem; } }). const mappedItems = items:map(item => { return { lineId. item,lineId: name. item.lineId,split(".").map(lineItem => mappedLines[lineItem].name || "").filter(x => x),join(";") }; }); return mappedItems. } console:log("Mapped Names,\n", mapNames(lines; items));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.