[英]How to find and match a specific value in a JSON object array?
我見過很多類似的問題,但似乎沒有什么與我正在嘗試做的完全匹配。 我能夠讓代碼正常工作,但我覺得它需要重構,但我不確定該怎么做?
我有兩個 for in 循環遍歷 JSON 以獲取我稱為項目的每個對象。 這行得通,但我無法執行另一個循環或想出一種方法來根據特定屬性獲取項目的值之一。 所以我從我在這里找到的一些代碼創建了一個函數: Javascript: find an object in an array based on the object's property
我的問題是,這是編寫此代碼的正確方法,還是通過某種方式通過另一個嵌套循環有更好的方法,這是我最初嘗試的方法?
這是工作的Plunker
代碼:
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
$scope.items = {"GROUP":[
{"name":"Plan A","value":[163],"displayed":true},
{"name":"Plan B","value":[497],"displayed":true},
{"name":"Plan C","value":[324],"displayed":true},
{"name":"Plan D","value":[476],"displayed":true},
{"name":"Plan E","value":[343],"displayed":true}]};
for (var key in $scope.items) {
console.log("key is: " + key + " " + JSON.stringify($scope.items[key]));
var item = $scope.items[key];
for(var itemKey in item){
//item is part of an object array
console.log("item is an array: " + JSON.stringify(item));
//itemKey is the number
console.log("itemKey is: " + itemKey);
//Each item in the GROUP
console.log("Each item: " + JSON.stringify(item[itemKey]));
//The names in the items.
console.log("The item name is: " + JSON.stringify(item[itemKey].name));
}
var objItem = findObjectByKey(item, 'name', 'Plan B');
console.log("objItem is: " + JSON.stringify(objItem));
console.log("objItem name is: " + JSON.stringify(objItem.name));
console.log("objItem value is: " + JSON.stringify(objItem.value));
console.log("objItem displayed is: " + JSON.stringify(objItem.displayed));
}
function findObjectByKey(array, key, value) {
for (var i = 0; i < array.length; i++) {
if (array[i][key] === value) {
return array[i];
}
}
return null;
}
});
這是控制台輸出
key is: GROUP [
{"name":"Plan A","value":[163],"displayed":true},
{"name":"Plan B","value":[497],"displayed":true},
{"name":"Plan C","value":[324],"displayed":true},
{"name":"Plan D","value":[476],"displayed":true},
{"name":"Plan E","value":[343],"displayed":true}]
itemKey is: 0
itemKey is: 1
itemKey is: 2
itemKey is: 3
itemKey is: 4
itemKey is: 5
The item name is: "Plan A"
The item name is: "Plan B"
The item name is: "Plan C"
The item name is: "Plan D"
The item name is: "Plan E"
這是我要選擇的數據。
objItem 是:{ "name":"Plan B","value":[497],"displayed":true }
objItem 名稱是:“Plan B”
objItem 值為:[497]
顯示的 objItem 是:true
GROUP
,您可以使用find
函數和some
函數,如下所示。 let items = {"GROUP":[ {"name":"Plan A","value":[163],"displayed":true}, {"name":"Plan B","value":[497],"displayed":true}, {"name":"Plan C","value":[324],"displayed":true}, {"name":"Plan D","value":[476],"displayed":true}, {"name":"Plan E","value":[343],"displayed":true}]}, key = 'Plan B', object = items.GROUP.find(o => Object.entries(o).some(([k, value]) => k === 'name' && value === key)); console.log(object);
.as-console-wrapper { max-height: 100%;important: top; 0; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.