Home > Enterprise >  Fill empty objects with non-empty object
Fill empty objects with non-empty object

Time:10-26

i have an object data like this in my javascript code. When i have keys with filled values like title_en and description_en, i want to copy of its content to title_fr and description_fr.

This is my data

{
    "id": "2331",
    "title_en" : "Something great"
    "title_fr": "",
    "description_en" : "Lorem ipsum something etc."
    "description_fr": "", 
    "tag_en": "im filled",
    "tag_fr": "another filled",


}

this is how it should be

{
    "id": "2331",
    "title_en" : "Something great"
    "title_fr": "Something great",
    "description_en" : "Lorem ipsum something etc."
    "description_fr": "Lorem ipsum something etc.",
    "tag_en": "im filled",
    "tag_fr": "another filled",
}

how can i accomplish this with jquery or js?

CodePudding user response:

This should replace any _fr with its _en counterpart. I would personally check not just equality to "", but also possible undefined. But it depends on your data structure.

let data = {"id": "42", "title_en": "something mildly great", "title_fr": "", "tag_en": "im filled...",  "tag_fr": ""};

Object.keys(data).forEach(key => {
  if (key.endsWith("_en")){
    const frKey = key.replace("_en", "_fr");
    if (data[frKey] === ""){
      data[frKey] = data[key];
    } 
  }
});

console.log(data);

CodePudding user response:

After spending a good time to work on this requirement, Here I am with the solution. Please give a try to this solution. It will work for multiple substrings separated by underscore as well.

Live Demo (Descriptive comments has been added into the below code snippet) :

const obj = {
  "id": "2331",
  "title_en" : "Something great",
  "title_fr": "",
  "description_en" : "Lorem ipsum something etc.",
  "description_fr": "", 
  "tag_en": "im filled",
  "tag_fr": "another filled"
}

// Iterating over object keys
Object.keys(obj).forEach(key => {
  // checking for the keys which dont have values
  if (!obj[key]) {
    // storing key in a temporary variable for future manipulations. 
    const temp = key;
    // Now splitting the key based on underscore.
    const splittedStr = temp.split('_');
    // now creating substring which will contain without lingual. i.e _en, _fr
    const concatStr = splittedStr.slice(0, splittedStr.length - 1).join('_')
    // assigning the value dynamically to the empty keys.
    obj[key] = (splittedStr.at(-1) === 'fr') ? obj[`${concatStr}_en`] : obj[`${concatStr}_fr`]
  }
});

// output
console.log(obj);

  • Related