简体   繁体   中英

How to change the value of property using reducer function

I wanted to change the value of sample based on the length of validators in the below given

Original:

object1 = {test1:{sample: ["0"], validators: {length: 2}},
    test2: {sample: ["1"], validators: {length: 1}}}

Expected Result:

object1 = {test1:{sample: ["0", "1"], validators: {length: 2}},
test2: {sample: ["0"], validators: {length: 1}}}

Code:

    Object.keys(object1).reduce((acc.test) => ({
        ...acc, 
        [test]:{
           ...test,
           sample:Array(validators.length).fill(null).map((_, i) => i.toString)
        }
    }, {}));

You can achieve it using map :

Object.keys(object1)
  .map(el => ({
    ...object1[el],
    sample: Array(object1[el].validators.length).fill(null).map((_, i) => i.toString())
  }));
    [validator]: {

              validations: Array(validators.length)

                .fill(null)

                .map((_, i) => i.toString()),

              validators,

            }

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