1

I would like to implement the existing object sampleobj as shown in expected output. I have key jan, feb, mar,apr and value seperated with commas, should take always first string as begin and second as end

"jan": "07:30,23:00" // begin,end

to

"jan_begin": "07:30", "jan_end": "23:00",

let res ={};
Object.keys(sampleobj).forEach(key => {
  Object.assign({},key_begin: sampleobj[key].split(",")[0], key_end: sampleobj[key].split(",")[1])
})
var sampleobj = {
  "jan": "07:30,23:00"
  "feb": "08:30,23:00"
  "mar": "07:30,22:00"
  "apr": ""
  "30-12-2019": "10:00,24:00",
  "31-12-2019": "11:00,24:00"
}

Expected Output:

{
  month:{
   "jan_begin": "07:30",
   "jan_end": "23:00",  
   "feb_begin": "08:30",
   "feb_end": "23:00", 
   "mar_begin": "07:30",
   "mar_end": "22:00",    
   "apr": "",
  },
  fields: [
   {date: "30-12-2019", begin: "10:00", end: "24:00"},
   {date: "31-12-2019", begin: "11:00", end: "24:00"},
  ]
 }

1 Answer 1

2

You could check the value first and then decide for an empty string or take splitted begin/end values.

var object = { jan: "07:30,23:00", feb: "08:30,23:00", mar: "07:30,22:00", apr: "", "30-12-2019": "10:00,24:00", "31-12-2019": "11:00,24:00" },
    result = Object
        .entries(object)
        .reduce((r, [k, v]) => {
            if (v === '') {
                r.month[k] = '';
                return r;
            }
            var [begin, end] = v.split(',');
            if (k.length === 3) {
                r.month[k + '_begin'] = begin;
                r.month[k + '_end'] = end;
            } else {
                r.fields.push({ date: k, begin, end });
            }
            return r;
        }, { month: {}, fields: [] });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

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.