简体   繁体   中英

Facing issues to get matched element in same order from Json Object array

I am having string with column names and trying to get value of matched element from the json object with key,value

var str=""Object Status","Reason","Date From","Date To","Object Number",";

I am having Json Object inside an array

dataResult.Objects[0]={OBJECT_NUMBER:123,OBJCET_STATUS:"NEW",DATE_FROM:"/Date(1587764199000)/",DATE_TO:"/Date(1619755200000)/",REASON:"FRESHCOPY"}

I am trying to loop through array and try to get matched element but I shoudl be expecting them in the same order as the string values are present.

for (var i = 0; i <= dataResult.Objects.length; i++) {
            var item = dataResult.Objects[i - 1];
            var val = '';
            $.each(item, function (key, value) {
                var columnCollection = str.replace(/ /g, "").toUpperCase();
                var matchingKey = key.replace(/_/g, '');
                if (columnCollection.includes(matchingKey)) {
                    val += '"' + value + '",';
                }
            });

            }

I tried with the above code snippet but I am getting result like "123,NEW,"/Date(1587764199000)/","/Date(1619755200000)/",FRESHCOPY" but I want the data tobe in same order as string. I am expecting the result should be "NEW,"FRESHCOPY","/Date(1587764199000)/","/Date(1619755200000)/",123"

Please let me know how can I achieve in the same order of string columns.

Wouldn't something like that work for you?

 const str=`"Object Status","Reason","Date From","Date To","Object Number"`, obj = {OBJECT_NUMBER:123,OBJECT_STATUS:"NEW",DATE_FROM:"/Date(1587764199000)/",DATE_TO:"/Date(1619755200000)/",REASON:"FRESHCOPY"}, result = str.split(',').map(key => obj[key.toUpperCase().replace(/\s/g, '_').replace(/"/g,'') ]) console.log(result)
 .as-console-wrapper{min-height:100%;}

Instead of looping through dataResult.Objects, loop through the str list and get the corresponding object from dataResult.Objects

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