我有上面這個陣列,我需要它的每一個屬性
。let arr = [{'John'/span>: 0}, {'Doe'/span>: 50}, {'marry': 100}]
一旦在理論上,我不知道其中任何一個鍵/值,我怎么能提取它的每一個鍵/值? 我已經嘗試過使用 object.keys,但它回傳的是我的陣列的索引。
uj5u.com熱心網友回復:
這應該是可行的
。const arr = [{'John'/span>: 0}, {'Doe'/span>: 50}, {'marry': 100}]。
//對arry中的每個元素進行迭代。
arr.forEach(a => {
//要遍歷元素物件中的每個鍵
Object.keys(a).forEach(k => {
///列印'k'鍵的值。
console.log(k ' : ' a[k])。
})
})
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
如果你想收集一個物件嵌套陣列的所有鍵和值,你可以使用Array.prototype.reduce,然后在單獨的嵌套陣列中收集嵌套物件的鍵和值,分別使用Object.key()和Object.value():
const arr = [{'John'/span>: 0}, {'Doe'/span>: 50}, {'marry': 100}]。
const allKeysAndValues = arr.reduce((acc, cur) => /span> {
acc.keys.push(...Object.keys(cur) )。
acc.values.push(...Object.values(cur) )。
return acc;
}, { keys: [], values: [] });
console.log(allKeysAndValues);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
1)你可以使用flatMap和Object.key來從一個物件陣列中獲取keys。
。let arr = [{ John: 0 }, { Doe: 50 }, { Marry: 100 }]。
const result = arr. flatMap((o) => Object.keys(o) )。)
console.log(result);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
2)要在一個陣列中找到所有的值
let arr = [{ John: 0 }, { Doe: 50 }, { Marry: 100 }]。
const values = arr. flatMap((o) => Object.values(o) )。)
console.log(values);
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
3)如果你想找出一個物件中的所有鍵和值
let arr = [{ John: 0 }, { Doe: 50 }, { Marry: 100 }]。
const result = {
keys: [],
values: [],
};
for (let obj of arr) {
Object.entries(obj).map(([k, v]) => /span> {
result.keys.push(k)。
result.values.push(v)。
});
}
console.log(result);
<iframe name="sif5" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
一個單行本可以是
。 let arr = [{'John'/span>: 0}, {'Doe'/span>: 50}, {'marry': 100}]
console.log( arr. map( obj => Object。 entries(obj));
<iframe name="sif6" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/327386.html
標籤:
