我想接收單個物件陣列,只回傳物件陣列中的非空值。
但是,我實作的方法在陣列中包含非空屬性并將它們作為陣列回傳。我怎樣才能讓它更容易?
我希望它作為物件回傳,而不是作為陣列回傳。
const arr = [{
text01 : 'name',
text02 : '[email protected]',
text03 : '010-1234-5678',
text04 : 'adress1',
text05 : 'adress2',
text06 : null,
text07 : null,
text08 : null,
},
{
text01 : 'name1',
text02 : '[email protected]',
text03 : '010-1255-5148',
text04 : 'adress3',
text05 : 'adress4',
text06 : null,
text07 : null,
text08 : null,
}]
getDataArr(arr) {
arr.forEach(item => {
const aaa = [];
for (let key in item) {
if (item[key] !== null) {
const value = item[key];
aaa.push({ key, value });
}
}
console.log(aaa);
});
// Get the value as const arr = [{
text01 : 'name',
text02 : '[email protected]',
text03 : '010-1234-5678',
text04 : 'adress1',
text05 : 'adress2',
},
{
text01 : 'name1',
text02 : '[email protected]',
text03 : '010-1255-5148',
text04 : 'adress3',
text05 : 'adress4',
}]
},
uj5u.com熱心網友回復:
您可以從物件陣列中過濾空物件、未定義和空值,如下所示:
const data = [
{name: "joe", age:99},
{name: "jack", age:8},
undefined,
{name: "lola", age:54},
{},
null
]
function getValidArray(arr){
return arr.filter(obj=> {
if(!!obj && typeof obj === "object"){
return Object.keys(obj).length > 0
}
return !!obj
})
}
console.log(getValidArray(data))
uj5u.com熱心網友回復:
您可以使用filter和map作為單行輕松實作結果:
arr.map((obj) =>
Object.fromEntries(Object.entries(obj).filter(([k, v]) => v !== null))
);
const arr = [
{
text01: 'name',
text02: '[email protected]',
text03: '010-1234-5678',
text04: 'adress1',
text05: 'adress2',
text06: null,
text07: null,
text08: null,
},
{
text01: 'name1',
text02: '[email protected]',
text03: '010-1255-5148',
text04: 'adress3',
text05: 'adress4',
text06: null,
text07: null,
text08: null,
},
];
const result = arr.map((obj) => Object.fromEntries(Object.entries(obj).filter(([k, v]) => v !== null)));
console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/400865.html
標籤:javascript 数组
上一篇:C 中如何列印和修改char
下一篇:在二維陣列的情況下查找索引
