Forum Discussion

ash42's avatar
ash42
New Contributor III
3 years ago
Solved

Create a Json from two seperate arrays Key and value

HI i have two arrays : 1.Name and 2. Values Names = [ “key1”,“key2”,“key3” ] Values = [ “Value1”,“Value2”,“Value3” ] I want output from snap as {“key1” : “value1”, “key2” :“value2”...
  • Aleksandar_A's avatar
    3 years ago

    Hi @darshthakkar,

    One approach will be to Map the input document with the following expression:

    $.entries().sort((a,b) => a[0].localeCompare(b[0])).reduce((acc,curr) => acc.extend({[curr[0]]:curr[1]}),{})
    

    Note: This will only sort properties on first level.

    Let me know if this helps.

    BR,
    Aleksandar.

  • darshthakkar's avatar
    3 years ago

    As we cannot mark multiple suggestions as “Solutions”, wanted to summarize the solution that will work for this use case:

    1. $.entries().sort((a,b) => a[0].localeCompare(b[0])).reduce((acc,curr) => acc.extend({[curr[0]]:curr[1]}),{})

    2. $.keys().sort().toObject((k,i)=> k, (k,i)=> $.get(k))

    Both the expressions mentioned above will ONLY work if we are at the last stage of the hierarchy.

    How I broke the hierarchy: Using JSON Splitter to reorganise JSON - #3 by Supratim

    Thank you @AleksandarAngelevski , @alchemiz and @Supratim for your inputs. Closing this thread now.