服務器給出以下回應:
SomeObject:{
Object1:{
id: 123456789,
name: "Foo"
},
Object2:{
id: 123456789,
name: "Bar"
}
}
是否有可能遍歷SomeObject和顯示兩個id和name的Object1/Object2?搜索這個主要導致使用Object.keys(SomeObject).map但是這些用于獲取Object1/Object2.
uj5u.com熱心網友回復:
const SomeObject = { Object1: { id: 123456789, name: "Foo" }, Object2:{ id: 123456789, name: "Bar" } };
const res =
Object.values(SomeObject)
.forEach(({ id, name }) => console.log(id, name));
uj5u.com熱心網友回復:
一種方法是使用 Object.values 然后使用 forEach。
SomeObject = {
Object1:{
id: 123456789,
name: "Foo"
},
Object2:{
id: 123456789,
name: "Bar"
}
}
Object.values(SomeObject).forEach(function (value) {
console.log(value.id);
//value.name
});
uj5u.com熱心網友回復:
您可以使用 for-in 回圈來迭代物件
for ( let index in SomeObject ) {
for ( let sub_index in SomeObject[ index ] ) {
console.log( 'index', index, 'SomeObject[ index ]', SomeObject[ index ] )
console.log( 'sub_index', sub_index, 'SomeObject[ index ][ sub_index ]', SomeObject[ index ][ sub_index ] )
}
}
uj5u.com熱心網友回復:
另一種使用兩個 forin 回圈的方法。
obj = {
SomeObject: {
Object1: {
id: 123456789,
name: "Foo"
},
Object2: {
id: 123456789,
name: "Bar"
}
}
}
for (const key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
const
obj2 = obj[key];
for (const key2 in obj2) {
if (Object.hasOwnProperty.call(obj2, key2)) {
inner_obj2 = obj2[key2];
console.log(inner_obj2.id, inner_obj2.name);
}
}
}
}
uj5u.com熱心網友回復:
因此,如果您有一個具有未知數量屬性的物件,但您知道所有這些屬性都是物件,您可以執行此操作...
let obj = {
prop1: {
id: 1,
someProp: { subId: 's1' }
},
propA: {
id: 2,
someProp: { subId: 's2' }
},
prop3: {
id: 3,
someProp: { subId: 's3' }
}
}
/**
* Recursively iterate an object and its properties.
* @param {object} theObj the object to be iterated
*/
function iterate(theObj) {
for (const key of Object.keys(theObj)) {
console.log(`type of ${key} = ${typeof theObj[key]}`);
// do something
if (typeof theObj[key] == 'object') {
iterate(theObj[key]);
}
}
}
iterate(obj);
// output
// type of prop1 = object
// type of id = number
// type of someProp = object
// type of subId = string
// type of propA = object
// type of id = number
// type of someProp = object
// type of subId = string
// type of prop3 = object
// type of id = number
// type of someProp = object
// type of subId = string
它絕不是完美的,但它適用于物件和陣列。甚至用這種瘋狂嘗試過。
let arr = [
0,
'test',
{
id: 1,
subarr: [
32,
45,
76
],
subObj: {
key:'foo',
lock: 'bar'
}
}
]
iterate(arr);
// output
// type of 0 = number
// type of 1 = string
// type of 2 = object
// type of id = number
// type of subarr = object
// type of 0 = number
// type of 1 = number
// type of 2 = number
// type of subObj = object
// type of key = string
// type of lock = string
uj5u.com熱心網友回復:
解決這個問題的關鍵是Object.values()方法,其結果可以使用for..ofor.forEach()回圈進行迭代:
const SomeObject = { Object1: { id: 123456789, name: "Foo" }, Object2:{ id: 123456789, name: "Bar" } };
for( let {id,name} of Object.values( SomeObject ) ) {
console.log( id, name );
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/376508.html
標籤:javascript 数组 打字稿 目的
上一篇:如何在JS中按值查找物件中的專案
