簡體   English   中英

如何僅從 object 中獲取值而忽略 NodeJS 中的 null 值?

[英]How to fetch only the values from an object ignoring the null values in NodeJS?

我有一個 object saResponse ,如下所示:

0: {severity: "Low", assignee: null, notesType: "Type1", notes: "Notes1", createdAt: "2020-07-29"}
length: 1

我想將此 Object 轉換為字符串,以便僅顯示由::分隔的值並忽略null值。

所需 Output

Low::Type1::Details1::2020-07-29

我添加了下面的代碼,但它沒有給出所需的 output

 const saValue = Object.values(saResponse).map
                (el => Object.entries(el).filter(([key, value]) => value !== null).reduce((acc, [key, value]) => ({
                    ...acc,
                    [key]: value
                }), {}));
const saStringValue = JSON.stringify(saValue);

根據我從您的帖子和評論中可以推斷出的內容,我認為變量saResponse的結構是這樣的:

響應

您有一個數組,其中只有一個項目,因為length屬性的值為1 其中的項目是object

現在,在您的情況下,您只有一個項目,但我發布了兩種場景的答案,您只有一個項目,而在第二個場景中,數組中有多個項目。 請根據您的需要對下面的代碼片段進行適當的更改。

let saResponse = [
    { severity: "Low", assignee: null, notesType: "Type1", notes: "Notes1", createdAt: "2020-07-29" },
    { severity: "High", assignee: 'john', notesType: null, notes: "Notes1", createdAt: "2020-06-27" }
];

// For array with only one element
let result = Object.values(saResponse[0]).filter(el => el !== null).join('::');

// For array with multiple elements
let result2 = saResponse.map(obj => Object.values(obj).filter(el => el !== null).join('::'))

此外,我僅針對null測試了該值,因為您特別提到您不想要null值。 但是,我不確定您是否對虛假值有一個好主意,因為在 javascript 中的許多虛假值中, null就是其中之一。 其他虛假值是undefined0""(empty string)false等。如果您想了解更多信息,請閱讀內容。

如果您不想要任何虛假值,那么您可以簡單地將.filter(el => el !== null)替換為.filter(el => el)

我認為這應該可行並使其更容易。

 const saResponse = { 0: {severity: "Low", assignee: null, notesType: "Type1", notes: "Notes1", createdAt: "2020-07-29"}, 1: {severity: "High", assignee: "meallhour", notesType: null, notes: "Notes1", createdAt: "2021-07-29"}, }; const saValue = Object.values(saResponse).map((row) => Object.values(row).filter(val => val).join('::') ).join(','); console.log(saValue);

// i have tried this and it work, but i cannot get where you get `Details 1` string?
const object1 = {severity: "Low", assignee: null, notesType: "Type1", notes: "Notes1", 
createdAt: "2020-07-29"};

const arr = Object.values(object1);
const filtered = arr.filter( el=>( 
   el != null)
);

console.log(filtered.join('::'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM