0

I have the following array in a JSON file, is there a way to replace each 'TODO' with the entry above it. For example, the first "TODO" should be "Previous question" and the second should be "Next question".

   [
      {          
        "englishDefault": "Previous question",
        "default": "TODO"
      },
      {
       "englishDefault": "Next question",
       "default": "TODO"
      }
    ]
8
  • Hm.. Why do you need to get 2 entry with the same String ? + We need to know which language you use to process your json Commented Oct 17, 2016 at 9:39
  • When you say "the entry above it", will it always be the entry with the "englishDefault" key, or may it change? Commented Oct 17, 2016 at 9:40
  • @Aks, I'm using javascript. Commented Oct 17, 2016 at 9:42
  • @Aaron, it will always be "englishDefault". Commented Oct 17, 2016 at 9:42
  • As a side note, it's not a JSON array, it's just a JavaScript array ; JSON (JavaScript Object Notation) is the serialized form of a JavaScript Object, where you represent it as a String. I assume you're not working on a String but rather on the native array Commented Oct 17, 2016 at 9:44

2 Answers 2

1

Here's how I would do it :

// with ES6
myArray.filter(i => i.default === "TODO").forEach(i => i.default = i.englishDefault);

//without ES6
for (var i=0; i<myArray.length; i++) {
    var cur = myArray[i];
    if (cur.default === "TODO") { cur.default = cur.englishDefault; }
}
Sign up to request clarification or add additional context in comments.

4 Comments

It should only write over the default property if it is set to "TODO" tho
@Aaron, great answer. Is there a way to extend it to nested instances of "englishDefault"?
Yeah sure : you could test whether the current object's "englishDefault" field is defined ( !== undefined) and if it's not the case browse the object's field in search for an object with an "englishDefault" field
Thanks, I wasn't sure how to browse the object. I created a different question that explains my problem better: stackoverflow.com/questions/40086058/…
0

Improving @Aaron answer, you can use a for each and a ternary operator.

for each (question in myArray) { question.default == "TODO" ? question.default = question.englishDefault : null; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.