简体   繁体   English

如何更新 JSON 数组中的属性 - Ramdajs

[英]how to update a property in JSON array - Ramdajs

Input:输入:

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

Output: Output:

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

Identify a particular message "C1" (substring) and update the string or set to null in array of objects识别特定消息“C1”(子字符串)并更新字符串或在对象数组中设置为 null

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?如何使用ifElse将第二条object消息设置为null?

You can evolve the each object in the array.你可以进化数组中的每个 object。 For each message try to match the message format that you need.对于每条message ,请尝试匹配您需要的消息格式。 If no match found (empty array) return null .如果未找到匹配项(空数组),则返回null If a match was found, take the 1st element from the results of R.match :如果找到匹配项, 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:动态使用 - 将 RegExp 作为参数传递:

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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