简体   繁体   中英

how to update a property in JSON array - Ramdajs

Input:

[{
    message: 'A1 Message, B1 Message, C1 Message'
}, {
    message: 'A1 Message, B1 Message'
}];

Output:

[{
    message: 'C1 Message'
}, {
    message: null
}];

Identify a particular message "C1" (substring) and update the string or set to null in array of objects

Tried the below:

var input = [{
    id: 1,
    message: 'A1 Message, B1 Message, C1 Message'
}, {
    id: 2,
    message: 'A1 Message, B1 Message'
}];

var updateMessage = (obj) => {
    var C1Message = R.pipe(
        R.prop('message'),
        R.splitAt(obj.message.indexOf('C1')),
        R.last
    )(obj);
    return R.assoc('message', C1Message, obj);
}

var updateArray = R.map(R.when(R.pipe(R.prop('message'), R.includes('C1')), updateMessage));
var output = updateArray(input);
console.log(output);

How to use ifElse to set the second object message as null?

You can evolve the each object in the array. For each message try to match the message format that you need. If no match found (empty array) return null . If a match was found, take the 1st element from the results of R.match :

 const { map, evolve, pipe, match, ifElse, isEmpty, always, head } = R const fn = map(evolve({ message: pipe( match(/C1[^,]+/), // match C1 message ifElse(isEmpty, always(null), // if empty assign null head // if not take the 1st element ) ) })) const data = [{ message: 'A1 Message, B1 Message, C1 Message' }, { message: 'A1 Message, B1 Message' }]; const result = fn(data) console.log(result)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Dynamic use - pass the RegExp as a parameter:

 const { map, evolve, pipe, match, ifElse, isEmpty, always, join } = R const fn = regexp => map(evolve({ message: pipe( match(regexp), // match a RegExp ifElse(isEmpty, always(null), // if empty assign null join(', ') // if not convert to a string ) ) })) const data = [{ message: 'A1 Message, B1 Message, C1 Message 1, C1 Message 2' }, { message: 'A1 Message, B1 Message' }]; const result = fn(/C1[^,]+/g)(data) console.log(result)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM