skip to Main Content

I am trying to change my array of object values with my object values through the key

let a = [
  {
    title: "rewardValue",
    value: "1",
  },
  {
    title: "rewardValue2",
    value: "10",
  },
  {
    title: "rewardValue2",
    value: "12",
  },
];

let aofValue = {
  rewardValue: "200",
  rewardValue2: "500",
  rewardValue3: "800"
};


a.map((val,index) => {


    if(val.title === Object.keys(aofValue)[0]) {

        val.value = aofValue.rewardValue

    }
    if (val.title === Object.keys(aofValue)[1]) {
      val.value = aofValue.rewardValue2;
    }

    if (val.title === Object.keys(aofValue)[2]) {
      val.value = aofValue.rewardValue3;
    }

})

console.log(a);

I got what I expected but is there any shorted way to do this ´?
I think the way which I done is completely wrong but it return what I expected any other possible solution for this and if available kindly explain the solution

3

Answers


  1. Directly use Array#map, replacing the value with the property value for the title in the object (accessed with bracket notation).

    let a=[{title:"rewardValue",value:"1"},{title:"rewardValue2",value:"10"},{title:"rewardValue2",value:"12"},],
        aofValue={rewardValue:"200",rewardValue2:"500",rewardValue3:"800"};
    let res = a.map(o => ({...o, value: aofValue[o.title]}));
    console.log(res);
    Login or Signup to reply.
  2. Try like below:

    let a = [ { title: "rewardValue", value: "1", }, { title: "rewardValue2", value: "10", }, { title: "rewardValue2", value: "12", }, ];
    let aofValue = { rewardValue: "200", rewardValue2: "500", rewardValue3: "800" };
    
    const output = a.map((item) => {
        return {
            ...item,
            value: aofValue[item.title],
        };
    })
    
    console.log(output)
    Login or Signup to reply.
  3. A possible solution:

    const aofKeys = Object.keys(aofValue);
    let aofKey;
    
    for (let row of a) {
      if ((aofKey = aofKeys.indexOf (row.title)) !== -1 )  {
        row.value = aofValue[aofKeys[aofKey]];
      }
    }
    

    This solution takes into account the fact that title of array a may not be present in aofValue

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search