[英]How to get a value of nested array inside object?
我的值是在對象內部和嵌套數組中。 任務是如果值匹配,那么它應該返回整個對象。 找到值[“ 320”]並返回該對象。
var myObj = {
"name":"John",
"age":30,
"cars": [
{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
{ "name":"BMW", "models":[ ["320"], "X3", "X5" ] },
{ "models":[{ "test": "abcd", key:[{bcc:'hello'}] } , "Panda"] }
]
}
這就是我所做的
myObj.cars.find(i => i.models.find(j=>j===["320"]))
預期結果
{name: "BMW", models: Array(3)}
您不能使用===
(或==
)來比較兩個不同的數組。 它將檢查它們是否是相同的數組,而不是等效的數組。
奇怪的是, models
某些條目是數組,其他條目是對象,而另一些條目是簡單的字符串。
要求您查找["350"]
也很奇怪。 這是否意味着您應該找到適合該陣列中所有模型的汽車? 還是其中任何一個? 數組只有一個條目並不重要,但是數組本質上可以有多個條目...
而且奇怪的是,有一個條目中的cars
,它沒有name
。
假設它應該是“ any”,那么您需要考慮到以下事實: models
中的某些條目是數組,而其他不是。
var myObj = { "name":"John", "age":30, "cars": [ { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] }, { "name":"BMW", "models":[ ["320"], "X3", "X5" ] }, { "models":[{ "test": "abcd", key:[{bcc:'hello'}] } , "Panda"] } ] }; const modelsToFind = ["320"]; const result = myObj.cars.find(car => car.models.find(model => { // If it's not an array, make it one if (!Array.isArray(model)) { model = [model]; } // Does it have any of the models we want? return model.some(m => modelsToFind.includes(m)); }) ); console.log(result);
這不能處理非數組對象models
中的條目。 目前尚不清楚對象應該看什么屬性。
總的來說,這個問題看起來很奇怪。
在進行比較之前,必須檢查內部項目是否為數組,然后可以使用Array.prototype.includes()檢查內部數組是否也包含您的值:
const myObj = { "name":"John", "age":30, "cars": [ { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] }, { "name":"BMW", "models":[ ["320"], "X3", "X5" ] }, { "models":[{ "test": "abcd", key:[{bcc:'hello'}] } , "Panda"] } ] }; const find = (obj, val) => obj.cars.find(i => i.models.find(j => Array.isArray(j) ? j.includes(val) : j === val )); console.log(find(myObj, '320')); console.log(find(myObj, 'X3'));
您能找到的最簡單,最短的答案。
myObj.cars.find(i => i.models.find( j=>Array.isArray(j) && j.includes("320")) )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.