简体   繁体   中英

Javascript - Convert JSON Object Property Value from Array to String

I have an issue where an API call I'm using is sending objects with one property that contains a single array value ( keys property in response below). Unfortunately I cannot use this format as I must abide by Nested arrays in order to use the outputted values in a separate application like so [[value1, value2, value3, value4],[value1, value2, value3, value4]] . I plan on asking a separate question to tackle the nested array section unless someone thinks it is an easy fix (I believe I should use .map to convert the object).

Here is the format of my objects (from console.log(searchQueries) ):

[ { keys: [ 'hammer' ],
    clicks: 1369,
    impressions: 3151,
    ctr: 0.4344652491272612,
    position: 1.004443033957474 },
  { keys: [ 'woodmaking' ],
    clicks: 207,
    impressions: 6324,
    ctr: 0.03273244781783681,
    position: 4.35831752055661 },
  { keys: [ 'house trends' ],
    clicks: 1,
    impressions: 3,
    ctr: 0.3333333333333333,
    position: 4.666666666666666 },
  { keys: [ 'housing' ],
    clicks: 1,
    impressions: 36,
    ctr: 0.027777777777777776,
    position: 6.472222222222222 } ]
byProperty

Above response is passed from the following for-in loop the result of this API response array being nested in an object originally:

for (var prop in res){
              searchQueries = res[prop];

              console.log(searchQueries);
}

Would the JSON.stringify method or .toString('keys') achieve what I'm looking for?

如果要将keys从数组转换为字符串,只需要遍历数组并进行更改:

searchQueries.forEach(function (obj) { obj.keys = obj.keys[0] })
 answer=Object.values(searchQueries).map(el=>{el.keys=el.keys[0];return Object.values(el)});
console.log(searchQueries);

https://jsbin.com/biyazunafu/1/edit?console

Loop over the main array, turn the Objects (el) keys array into a string, than turn the whole object into its values Array. However, Object.values is experimental, so may dont use this on the users side, instead use this code transpiled to ES5 :

answer=[];
for(key in searchQueries){
  answer.push(searchQueries[key]);
 }
answer=answer.map(function(el){
  el.keys=el.keys[0];
  var newel=[];
  for(key in el){
    newel.push(el[key]);
  }
 return newel;
});
  • 1st Get the keys values

     var keys = searchQueries.map(function(e){return e.keys;}); 

This will output :

[["hammer"], ["woodmaking"], ["house trends"], ["housing"]]
  • 2nd: Concat the resulting array

     var values = keys.join(',').split(','); 

The result :

 ["hammer", "woodmaking", "house trends", "housing"]

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