0

My Json is as below. I have four fields in my json.

[
 {
    "id": "name1",
    "c1": "10",
    "c2": "20",
    "c3": "30"
        },
    {
    "id": "name2",
    "c1": "20",
    "c2": "40",
    "c3": "25"
        }
]

My desired result is as below.

[
 {
    "id": "name1",
    "c1": "10",
    "c2": "20"
     "a1": "50"

        },
    {
    "id": "name2",
    "c1": "20",
    "c2": "40",
     "a1": "50"
        }
]

I want to map my 4th element with a new name.

indra257
  • 66
  • 3
  • 24
  • 50
  • not a lodash-based solution, but similar http://stackoverflow.com/questions/13391579/how-to-rename-json-key – Hypaethral May 15 '17 at 19:18
  • convert the JSON object to json String and then replace the name c3 with a1. – user3182536 May 15 '17 at 19:24
  • Here the fields are dynamic. The fourth field can have any name (not just c3). I need to rename it. . – indra257 May 15 '17 at 19:26
  • One way could be taking the first object in your array if it exists, use Object.keys(obj)[3] to get the correct fourth field name, and then do as the other solution suggests. As an aside, I'd suggest editing the question to specify this dynamic field requirement is part of your problem – Hypaethral May 15 '17 at 19:37
  • @GrumbleSnatch This idea helps. Thanks. – indra257 May 15 '17 at 20:08

2 Answers2

0

You can use lodash#map to iterate and modify each item of the collection. We use lodash#toPairs to convert the object into an array of key-values, update the value using lodash#update from the 4th value which is the 3rd index of the collection into ['a1', '50']. Lastly, use lodash#fromPairs to convert it back into an object.

var result = _.map(source, function(value) {
  return _(value)
    .toPairs()
    .update('3', _.constant(['a1', '50']))
    .fromPairs()
    .value();
});

var source = [{
    "id": "name1",
    "c1": "10",
    "c2": "20",
    "c3": "30"
  },
  {
    "id": "name2",
    "c1": "20",
    "c2": "40",
    "c3": "25"
  }
];

var result = _.map(source, function(value) {
  return _(value)
    .toPairs()
    .update('3', _.constant(['a1', '50']))
    .fromPairs()
    .value();
});
  
console.log(result);
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
ryeballar
  • 29,658
  • 10
  • 65
  • 74
0

Try this

var jsonObj = [
 {
    "id": "name1",
    "c1": "10",
    "c2": "20",
    "c3": "30"
        },
    {
    "id": "name2",
    "c1": "20",
    "c2": "40",
    "c3": "25"
        }
];

for (var i in jsonObj) {
  var keys = Object.keys(jsonObj[i])[3];
  delete jsonObj[i][keys];
  jsonObj[i]["a1"] = "50";
}

console.log(jsonObj);
Debug Diva
  • 26,058
  • 13
  • 70
  • 123