最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to combine multiple key values in JSON object? - Stack Overflow

programmeradmin3浏览0评论

I have this sample JSON object

var sample = [{
    "label": "one",
    "value": 1
}, {
    "label": "two",
    "value": 2
}, {
    "label": "three",
    "value": 3
}, {
    "label": "four",
    "value": 4
}, {
    "label": "five",
    "value": 5
}];

I want to change it some thing like this

var sample = [{
    "label": "one",
    "value": 1,
    "newKeyValue": "one|1"
}, {
    "label": "two",
    "value": 2,
    "newKeyValue": "two|2"
}, {
    "label": "three",
    "value": 3,
    "newKeyValue": "three|3"
},
...
];

It should combine both key values and return new key value combining both.

JSON is coming dynamically key label and value are not static it can be anything. For example [{"name":"srinivas","lastname":"pai"}]

I have this sample JSON object

var sample = [{
    "label": "one",
    "value": 1
}, {
    "label": "two",
    "value": 2
}, {
    "label": "three",
    "value": 3
}, {
    "label": "four",
    "value": 4
}, {
    "label": "five",
    "value": 5
}];

I want to change it some thing like this

var sample = [{
    "label": "one",
    "value": 1,
    "newKeyValue": "one|1"
}, {
    "label": "two",
    "value": 2,
    "newKeyValue": "two|2"
}, {
    "label": "three",
    "value": 3,
    "newKeyValue": "three|3"
},
...
];

It should combine both key values and return new key value combining both.

JSON is coming dynamically key label and value are not static it can be anything. For example [{"name":"srinivas","lastname":"pai"}]

Share Improve this question edited Jan 19, 2016 at 12:06 Tushar 87.2k21 gold badges163 silver badges181 bronze badges asked Jan 19, 2016 at 11:25 Shrinivas PaiShrinivas Pai 7,7014 gold badges31 silver badges57 bronze badges 5
  • try by $.extend(targetSample,Sample); – Parth Trivedi Commented Jan 19, 2016 at 11:26
  • @Tushar No not tried. – Shrinivas Pai Commented Jan 19, 2016 at 11:27
  • I tried using for loop only single value I can add @Tushar – Shrinivas Pai Commented Jan 19, 2016 at 11:29
  • The way you posted your question seems a little confusing. I suggest to add, that the actual keys are not static but can differ from time to time, as you already did in some comments. – T3 H40 Commented Jan 19, 2016 at 11:43
  • and how do you keep the order of the keys? – Nina Scholz Commented Jan 19, 2016 at 12:04
Add a comment  | 

6 Answers 6

Reset to default 4

You can use map like this :

EDIT

For handling generic keys you can use Object.keys(d)[0] for first key Object.keys(d)[1] for second key

var sample = [

     {
      "label":"one",
      "value":1
     },

     {
      "label":"two",
      "value":2
     },
     {
      "label":"three",
      "value":3
     },
     { 
      "label":"four",
      "value":4
     },
     { 
      "label":"five",
      "value":5
      }

     ];
    var data = sample.map(function(d){
     return {label: Object.keys(d)[0], value: Object.keys(d)[1], newKeyValue:  Object.keys(d)[0] +"|" + Object.keys(d)[1]}
    }) 
    console.log(data)

Hope this helps!

You can use Array#map(), Object.keys(), and Array#join().

In ES6, you can use Arrow functions.

sample = sample.map(obj => {
    var keys = Object.keys(obj);
    obj.newKeyValue = keys.map(key => obj[key]).join('|');
    return obj;
});

var sample = [{
    "label": "one",
    "value": 1
}, {
    "name": "two",
    "age": 2
}, {
    "five": "three",
    "six": 3
}, {
    "company": "four",
    "organization": 4
}, {
    "label": "five",
    "value": 5
}];

sample = sample.map(function (x) {
    var keys = Object.keys(x);
    x.newKeyValue = keys.map(key => x[key]).join('|');
    return x;
});
console.log(sample);
document.body.innerHTML = '<pre>' + JSON.stringify(sample, 0, 4) + '</pre>';

In ES5, you can use the same code with anonymous functions

sample = sample.map(function (obj) {
    var keys = Object.keys(obj);
    obj.newKeyValue = keys.map(function (key) {
        return obj[key]
    }).join('|');
    return obj;
});

Limitations due to dynamic keys:

  1. The order of the keys in object cannot be maintained
  2. This will join all the available keys in the object (in case if you just want to join fewer)

var sample = [

         {
          "label":"one",
          "value":1
         },

         {
          "label":"two",
          "value":2,
          "optionalValue":2
         },
         {
          "label":"three",
          "value":3,
          "remarks":"free text"
         },
         { 
          "label":"four",
          "value":4
         },
         { 
          "label":"five",
          "value":5
          }

         ];

    for (var key in sample) {
      var newValue = [];
      for (var piece in sample[key]){
        newValue.push(sample[key][piece])
      }
      sample[key]["newKeyValue"] = newValue.join('|');
    }

    $('pre').html(JSON.stringify(sample,null,4));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre></pre>

You can use Array.prototype.forEach() for in situ changes.

The forEach() method executes a provided function once per array element.

Edit: with dynamic keys, stored in an array, because of the order.

var sample = [{ "label": "one", "value": 1 }, { "label": "two", "value": 2 }, { "label": "three", "value": 3 }, { "label": "four", "value": 4 }, { "label": "five", "value": 5 }];

sample.forEach(function (a) {
    a.newKeyValue = ['label', 'value'].map(function (k) { return a[k]; }).join('|');
});

document.write('<pre>' + JSON.stringify(sample, 0, 4) + '</pre>');

If more element are their then use $.extend

var sample = [

         {
          "label":"one",
          "value":1
         },

         {
          "label":"two",
          "value":2
         },
         {
          "label":"three",
          "value":3
         },
         { 
          "label":"four",
          "value":4
         },
         { 
          "label":"five",
          "value":5
          }

         ];
        $(sample).each(function(i,item){
            var keyes = Object.keys(item);
            sample[i] =  $.extend(item,{newKeyValue: item[keyes[0]] +"|" +item[keyes[1]]});
        });
       
        console.log(sample)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

$.extend also helpful when you are having more objects already and you want to merge both eg.

  var base  = {
          "label":"one",
          "value":1
         }

and you want to add more objects

 var extra  =  {
          "new1":"value1",
          "new2":"value2",
          "new3":"value3",
          "new4":"value4",
       }

then it will be done by

$.extend(base,extra);

Output:

        {
              "label":"one",
              "value":1,
              "new1":"value1",
              "new2":"value2",
              "new3":"value3",
              "new4":"value4",
         }
var sample = [{"name":"srinivas","lastname":"pai"}];    

sample.map(function(item) {
  item.newKeyValue = Object.getOwnPropertyNames(item).map(function(d) {return item[d];}).join("|");
})

    console.log(sample);
发布评论

评论列表(0)

  1. 暂无评论