1

Is there a way I can create an object from this data stored in a string, coming from the google API:

   "recurrence": [
    "RRULE:FREQ=WEEKLY;UNTIL=20181213T235959Z;BYDAY=TH"
   ],

I can use string methods, but I wondered if there was a better way.

Something like:

recurrence: {
    frequency: "weekly",
    until: "yy/mm/dd",
    byday: "th"
}

Any ideas?

3
  • What is the desired object structure, based on the given string? Commented Nov 22, 2018 at 10:06
  • You could split on semicolon, which would give you an array of entries. Commented Nov 22, 2018 at 10:06
  • No way but string methods for this case. Commented Nov 22, 2018 at 10:11

4 Answers 4

1

The Google API Documentation itself provides no other format. Hence your only option would be to apply simple string transformations. Such as :

let targetObj = {};
for(const entry of res.recurrence.substr(5).split(';)) {
    const [key, value] = entry.split('=');
    targetObj[key] = value;
}
Sign up to request clarification or add additional context in comments.

Comments

0

You will need to split multiple times and convert key to lower case.

var api = {"recurrence": ["RRULE:FREQ=WEEKLY;UNTIL=20181213T235959Z;BYDAY=TH"]};
var obj = {};
var str = api.recurrence[0];
var arr = str.split(";");
arr.forEach(function(element){

  var pair = element.split("=");
  var key_array = pair[0].split(":");
  var key = key_array[key_array.length-1].toLowerCase();
  var val = pair[1];
  obj[key]=val;
  
});

console.log(obj);

Comments

0

You can use a regex to match what you want and create your object.

const obj = { reference: ["RRULE:FREQ=WEEKLY;UNTIL=20181213T235959Z;BYDAY=TH"] };

const regex = /\w+=\w+/g;

const extract = (obj) =>
  
  obj.reference.reduce((acc, val) => {
    
    val.match(regex).forEach((match) => {
      
      const [lVal, rVal] = match.split('=').map(d => d.toLowerCase());
      
      acc[lVal] = rVal;
    });
    
    return acc;
  }, {});

console.log(extract(obj));

Comments

0

Look at my solution

var str1 = "RRULE:FREQ=WEEKLY;UNTIL=20181213T235959Z;BYDAY=TH";
var str2 = str1.split(':')[1].split(';');
  //  console.log(str2.split(';'));
var x = str2.map((s)=>{
    return s.split("=");
  });

var recurrence = {};
x.forEach((ar)=>{
  if(ar[0] == 'UNTIL')
    ar[1] = moment(ar[1]).format('DD/MM/YYYY');
  recurrence[ar[0]] = ar[1];
});

console.log(recurrence);
<script src="https://momentjs.com/downloads/moment.js"></script>

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.