简体   繁体   中英

Replace array/objects key value with key value from another array/object javascript

My question is based on how to merge data from one JS object into another JSON object in order to replace its current value by mapping that to a key and value from the other object.

In this example I have x and y which are simply giving a date and a number. However I also have 3 other keys who's value is the key within another object in the example below. Those keys are:

  • pf
  • nf
  • t

The goal is to either modify the current JSON object by replacing the value with the match keys value OR creating a new JSON object entire with those same replacement. The only other caveat is that sometimes the values from the original object with be null and in those cases they should remain null after the merge or creation of the new JSON.

        var data = [

                {x: Date.UTC(2014,8,1), y: 730, pf:["001","002"], nf:["001","002"], t:["001","002"] },
                {x: Date.UTC(2014,10,1), y: null, pf:null, nf:null, t:null},
                    ]


        var pfMap={
            "001":{"sd":"short desc1", "ld":"long desc1"}, 
            "002":{"sd":"short desc2", "ld":"long desc2"}
        }

        var nfMap={
            "001":{"sd":"short desc1", "ld":"long desc1"},
            "002":{"sd":"short desc2", "ld":"long desc2"}
        }

        var tMap={
            "001":"tip text1",
            "002":"tip text2"
        }

So as an example the new JSON object would have an array of the keys two results or null if nothing is there. Hopping this makes sense.

  var data = [ {x: Date.UTC(2014,8,1), y: 730, pf:["001","002"], nf:["001","002"], t:["001","002"] }, {x: Date.UTC(2014,10,1), y: null, pf:null, nf:null, t:null}, ] var pfMap={ "001":{"sd":"short desc1", "ld":"long desc1"}, "002":{"sd":"short desc2", "ld":"long desc2"} } var nfMap={ "001":{"sd":"short desc1", "ld":"long desc1"}, "002":{"sd":"short desc2", "ld":"long desc2"} } var tMap={ "001":"tip text1", "002":"tip text2" } //recursion function traverseData(data, elementName) { var keys = Object.keys(data); for (var i = 0; i < keys.length; ++i) { if ( Object.prototype.toString.call(data[keys[i]]) == "[object Object]" || Object.prototype.toString.call(data[keys[i]]) == "[object Array]") { traverseData(data[keys[i]], keys[i]); } else { if (elementName != null && window[elementName + "Map"]) { data[keys[i]] = window[elementName + "Map"][data[keys[i]]]; } } } } traverseData(data, "data"); document.write(JSON.stringify(data)); 

This recursive function will do the trick. It ignores null values. Otherwise when the object is a string and matches one of the map objects it will replace the value. You can go n levels deep with this function.

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