- 我是 js 新手。
- 我正在尝试迭代 json 结构。
- 当我看到 isDefault: true 时,我需要显示为默认名称。
- 但现在我正在 js 代码中硬编码值。
- 你能告诉我如何解决这个问题吗?
- 在下面提供我的代码。
data.downlinkmoons =[{Lion: 237, birds: "Animal Sports Bay Area", fish: 1, isDefault: true, wire: ""},
{Lion: 238, birds: "Animal Sports California", fish: 1, wire: ""},
{Lion: 239, birds: "Animal Sports Washington", fish: 1, wire: ""},
{Lion: 240, birds: "Animal Sports Philadelphia", fish: 1, wire: ""}]
playOutside(data: any) {
let that = this;
let tempObj = {};
//tempObj['Lion'] = 237;
tempObj['Lion'] = data.downlinkmoons[0].Lion;
tempObj['birds'] = 'Animal Sports Bay Area';
// tempObj['Lion'] = data.selectedLion;
// tempObj['birds'] = data.selectedbirds;
this.moonTempArray = [];
this.moonTempArray.push(tempObj);
let moonsdata = data.downlinkmoons;
let moonsDataList = this.moonTempArray;
let selectedmoon = moonsdata.find(elem => elem.Lion == 237);
this.downlinkBulkUpdateVal.Lion = 237;
// let selectedmoon = moonsdata.find(elem => elem.Lion == data.selectedLion);
// this.bulkCreateVal.Lion = data.selectedLion;
this.selectedmoonArr = selectedmoon;
this.moonCarousel.setmoonData(moonsdata, moonsDataList, 237);
//this.moonCarousel.setmoonData(moonsdata, moonsDataList, data.selectedLion);
$("#moonCarouselLabel .moonHint").css("display", "none");
setTimeout(function () {
$("#unSelectedmoonsLogoBox1 .currentNwLogo").bind("click", function (e) {
e.stopPropagation();
that.singleSelection(data, e);
});
}, 100);
}
最佳答案
您可以使用Array.prototype.find()
函数:
var downlinkmoons =[{Lion: 237, birds: "Animal Sports Bay Area", fish: 1, isDefault: true, wire: ""},
{Lion: 238, birds: "Animal Sports California", fish: 1, wire: ""},
{Lion: 239, birds: "Animal Sports Washington", fish: 1, wire: ""},
{Lion: 240, birds: "Animal Sports Philadelphia", fish: 1, wire: ""}];
function getDefault(downlinkmoons){
return downlinkmoons.find((elem) => { return elem.isDefault; });
}
console.log(getDefault(downlinkmoons))
有关 Array.prototype.find 的更多信息是 here .
关于javascript - 迭代 json 并找到特定的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49960347/