简体   繁体   中英

Combine two arrays into one by matching elements using Javascript

I have two arrays. One fetched from an API the other fetched from firebase. They both have a similar key inside of them, that being the tld. As seen below.

API Array

[
 {
  "tld" : "com",
  "tld_type": 1,
 },
  "tld" : "org",
  "tld_type" : 1,
 }
]

Firebase Array

[
  {
    "TLD" : "com",
    "register_price" : 14.99
  },
  {
    "TLD" : "org",
    "register_price" : 15.99
  }
]

I want to combine these two arrays into one and return it like below

[
    {
        "tld" : "com",
        "tld_type" : 1,
        "register_price" : 14.99
    },
    {
        "tld" : "org",
        "tld_type" : 1,
        "register_price" : 15.99
    }
]

I've done some google searching and found concact but that doesn't seem to be using the key to find the match. How would I do this?

You can use map and create a new object whose keys and values will be from the other two arrays and return that object. map will create a new array of objects

 let api = [{ "tld": "com", "tld_type": 1, }, { "tld": "org", "tld_type": 1, } ] let fb = [{ "TLD": "com", "register_price": 14.99 }, { "TLD": "org", "register_price": 15.99 } ] let k = api.map(function(item, index) { let obj = {}; obj.tld = item.tld; obj['tld_type'] = item['tld_type']; obj['register_price'] = fb[index]['register_price'] return obj; }); console.log(k) 

There is no unique method for solving that kind of issue. You'll have to loop through all elements and add register_price property if that property exists in firebase array. In shortest possible:

let combined = apiArray.map(ele=>{
    let machedElement = fbArray.find(e => e.TLD === ele.tld)
    if(machedElement != undefined) ele.register_price = machedElement.register_price
    return ele
})

In case if you want to merge all properties not only register_price:

let combined = apiArray.map(ele=>{
    let machedElement = fbArray.find(e => e.TLD === ele.tld)
    if(machedElement != undefined) {
       let mergedObject = Object.assign(ele, machedElement)
       return mergedObject
    }else{
       return ele
    }
})

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