简体   繁体   中英

How to create an object based on filtering two arrays with a filter criteria from one array in Javascript/ES6?

Let's assume I have two arrays of the same length:

const arr_one = [1,2,null,4,null,6];
const arr_two = ["a","b","c","d","e","f"];

Now I would like to create one object called arr_final out of it that uses the values of arr_two as keys and the values of arr_one as values for arr_final , but only for values in arr_one that are not null .

So the desired outcome would be:

const obj_final = {"a": 1, "b": 2, "d": 4, "f": 6}

Current solution

Currently, I am having a for loop with an if check inside it and would like to change it to a more shorter code:

let arr_final = {};
for (const [i, v] of arr_one.entries()) {
    if (v != null) {
        arr_final[arr_two[i]] = v
    }
};

How can I achieve this with a minimal number of code lines?

Here's the shortest one-liner approach, that requires 1 array iteration only

 const arr_one = [1,2,null,4,null,6]; const arr_two = ["a","b","c","d","e","f"]; const fa = arr_one.reduce((a, e, i) => e ? { ...a, [arr_two[i]]: e } : a ,{}); console.log(fa);

Your code looks optimal, here is an another version to your solution:

 const arr_one = [1,2,null,4,null,6]; const arr_two = ["a","b","c","d","e","f"]; let arr_final={} arr_one.map((itm,indx)=>{ if(itm!==null){ arr_final[arr_two[indx]]=itm } }) console.log(arr_final)

使用 lodash zipObject 实用程序这里是一个参考: https ://lodash.com/docs/4.17.15#zipObject

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM