从数组中删除空元素

时间:2019-01-17 10:31:16

标签: angular typescript

我正在获取值作为输入,并将它们作为数组推送到后端。前端的数组中有6个预定义的项。如果我发送6个值,则数组内不会有任何空元素。如果我发送的少于6个,则会创建一个空元素。这是一个已知的事实。现在,我想在推送数组之前过滤掉空元素。

实际输出

[
    {

        "ABC_Info": {
            "_id": "5c404e2d16e42513905189a1",
            "ABC": [
                {
                    "_id": "5c404e2d16e42513905189a7",
                    "a": "Dosa",
                    "b": 15,
                    "c": 30
                },
                {
                    "_id": "5c404e2d16e42513905189a6",
                    "a": "Idly",
                    "b": 25,
                    "b": 25
                },
                {
                    "_id": "5c404e2d16e42513905189a5",
                    "a": "Vada",
                    "b": 25,
                    "c": 35
                },
                {
                    "_id": "5c404e2d16e42513905189a4"
                },
                {
                    "_id": "5c404e2d16e42513905189a3"
                },
                {
                    "_id": "5c404e2d16e42513905189a2"
                }
            ]
        }
    }
]

TS

this.abcService.addabc(ABC).subscribe(
    res => {
        this.abcArray.push(res); //abcArray is a array. Before Pushing  I want to check for empty element and remove before pushing

    },
    error => console.log(error)
);
}

4 个答案:

答案 0 :(得分:2)

如果要在获取数据后创建数组,请在阵列上使用filter method

this.abcArray.filter(item => ...your predicate to say an item is non-empty...)

如果您可以控制何时推送项目,为什么不知道它们是非空的就简单地推送它们呢?

if (... your predicate non empty ...)
  this.abcArray.push(res)

答案 1 :(得分:2)

除了_id属性之外,您还想知道对象是否为空,因此可以执行以下操作:

res.ABC.filter(obj => {
  const keys = Object.keys(obj);
  return (keys.length !== 1  || keys[0] !== '_id') && keys.length !== 0;
});

答案 2 :(得分:1)

您可以使用数组过滤器:

public class MainActivity extends AppCompatActivity {

    // Variables for the search input field, and results TextViews.

    private RecyclerView mRecyclerView;
    private WordListAdapter mAdapter;
    private LinkedList<String> mWordList = new LinkedList<>();

    /**
     * Initializes the activity.
     *
     * @param savedInstanceState The current state data
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize all the view variables.

        mRecyclerView=(RecyclerView)findViewById(R.id.recyclerview);

        searchBooks(new View(this));
    }

    /**
     * Gets called when the user pushes the "Search Books" button
     *
     * @param view The view (Button) that was clicked.
     */
    public void searchBooks(View view) {
        // Get the search string from the input field.
        //String queryString = mBookInput.getText().toString();


        // Check the status of the network connection.
        ConnectivityManager connMgr = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        // If the network is active and the search field is not empty, start a FetchBook AsyncTask.
        if (networkInfo != null && networkInfo.isConnected()) {
            new FetchBook(mWordList).execute("Titanic");

            try { Thread.sleep(5000); }
            catch (InterruptedException ex) { android.util.Log.d("YourApplicationName", ex.toString()); }

            // Create recycler view.
            mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
            // Create an adapter and supply the data to be displayed.
            mAdapter = new WordListAdapter(this, mWordList);
            // Connect the adapter with the recycler view.
            mRecyclerView.setAdapter(mAdapter);
            // Give the recycler view a default layout manager.
            mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        }
        // Otherwise update the TextView to tell the user there is no connection or no search term.
        else {

        }
    }
}

答案 3 :(得分:1)

您可以根据每个项目中的属性计数使用过滤方法和过滤器数组,如下所示

dirname(__DIR__,level);
dirname(__DIR__,1);

没有任何可使用_id之类属性的过滤器数组元素

this.abcService.addabc(ABC).subscribe(
    res => {
        let res1 = res.filter(i=>Object.keys(i.ABC_Info.ABC).length >1);
        this.abcArray.push(res1); //abcArray is a array. Before Pushing  I want to check for empty element and remove before pushing

    },
    error => console.log(error)
);
}