1

Apologise if you feel the question is a bit lengthy. I have an array of objects in the following structure:

let arrObj = [{
        id: "test1",
        value1: "a1",
        value2: "b1",
    },
    {
        id: "test2",
        value1: "a2",
        value2: "b2",
    },
    {
        id: "test3",
        value1: "a3",
        value2: "b3",
    },
    {
        id: "test4",
        value1: "a4",
        value2: "b4",
    }
];

I basically have to replace object with id test2, test3,test4 based on some input passed, rest objects should be untouched. I have written a switch case that takes three values and then computes and then returns modified array of objects.

The values that are being passed on which modification should happen are abc,def,ghi.

Basically following values needs to be returned based on the input values The value1,value2 are just some hardcoded values

var res1 = updateValue(arrObj,"abc");
//result should be
 [{
        id: "test1",
        value1: "a1",
        value2: "b1",
    },
    {
        id: "test2",
        value1: "dsdsd",
        value2: "ghasgas",
    },
    {
        id: "test3",
        value1: "dsds",
        value2: "asasas",
    },
    {
        id: "test4",
        value1: "dsdsdsae",
        value2: "saheuwe",
    }
];

In similar way,

var res1 = updateValue(arrObj,"def");
//result should be
[{
        id: "test1",
        value1: "a1",
        value2: "b1",
    },
    {
        id: "test2",
        value1: "dshds67",
        value2: "sdjsahdj1213",
    },
    {
        id: "test3",
        value1: "jdshdjh123",
        value2: "dkshdksj88",
    },
    {
        id: "test4",
        value1: "hjwhekjwq2123",
        value2: "sjhdj2323",
    }
];

Also,

var res3 = updateValue(arrObj,"ghi");
//result should be
[{
        id: "test1",
        value1: "a1",
        value2: "b1",
    },
    {
        id: "test2",
        value1: "gahsddct21ew",
        value2: "gdsaedtsasa2re",
    },
    {
        id: "test3",
        value1: "gdsdssselectdsd",
        value2: "ghiasaselect3we",
    },
    {
        id: "test4",
        value1: "ghdsiselectdsdre",
        value2: "ghdsiselectr4"
    }
];

Code that I have tried:

function updateValue(obj, value) {
    let defaultObj = {
        id: ""
    }
    var newObj = {};
    switch (value) {
        case "abc":
            newObj.value1 = "abcselect21"
            newObj.value2 = "abcselect22"
            break;

        case "def":
            newObj.value1 = "defselect21";
            newObj.value2 = "defselect22"
            break;

        case "ghi":
            newObj.value1 = "ghiselect21";
            newObj.value2 = "ghiselect22"
            break;
    }

    finalArr = [{
        ...defaultObj,
        ...newObj
    }];
    return finalArr;
}
4
  • What is the issue here? Commented May 15, 2020 at 14:53
  • Unable to get the required result with my approach Commented May 15, 2020 at 14:54
  • You're missing a " at newObj.value1 = "defselect21; Commented May 15, 2020 at 14:55
  • Must have been a typo, still does not get me the required result Commented May 15, 2020 at 14:58

5 Answers 5

1

It's always challenging to answer questions where the data is simplified to a degree that it hides your original intention. Anyway, here's how I might break the problem down -

// generics
const identity = x => x

const update1 = (o = {}, [ k = "", t = identity ]) =>
  ({ ...o, [k]: t(o[k]) })
  
const update = (o = {}, patch = {}) =>
  Object.entries(patch).reduce(update1, o)

// specifics
const transform = ([ defaults, ...more ], str = "") =>
  [ defaults
  , ...more.map(item =>
      update(item, {
        value1: v => `${str}select${getId(v)}1`,
        value2: v => `${str}select${getId(v)}2`
      })
    )
  ]

const getId = (s = "") =>
  s.match(/\d+/) || 0

// test
const arrObj =
  [ {id:"test1",value1:"a1",value2:"b1"}
  , {id:"test2",value1:"a2",value2:"b2"}
  , {id:"test3",value1:"a3",value2:"b3"}
  , {id:"test4",value1:"a4",value2:"b4"}
  ]
  
const result =
  transform(arrObj, "xyz")
  
console.log(result)

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

Comments

0

Something like that could be helpful:

var arrObj = [
  {
    id: "test1",
    value1: "a1",
    value2: "b1"
  },
  {
    id: "test2",
    value1: "a2",
    value2: "b2"
  },
  {
    id: "test3",
    value1: "a3",
    value2: "b3"
  },
  {
    id: "test4",
    value1: "a4",
    value2: "b4"
  }
];

var keyList = ["test2", "test3", "test4"];
mapObject(keyList, "abc");

function mapObject(filterList, param) {
  let newArray = arrObj
    .filter(item => filterList.findIndex(val => val == item.id) != -1)
    .map(function(currentValue, index) {
      currentValue.value1 = param + "select" + (index + 1).toString() + "1";
      currentValue.value2 = param + "select" + (index + 1).toString() + "2";

      return currentValue;
    })
    .concat(
      arrObj.filter(item => filterList.findIndex(val => val == item.id) == -1)
    );

  console.log(newArray);
}

Check out the live demo:
https://stackblitz.com/edit/js-x1pwqh

3 Comments

the values that are shown in the expected ouput are for illustrational. Just to undertstand better. UPdating it now
In the mapping function (.map) you can apply any desired changes. Configure the mapObject function with the parameters useful to carry out the conversion.
now it will be switch case right? Because the values are not computed based on the value passed to the switch statement in the question
0

You should check the ids before updating the values. Try this function:

function updateValue(obj, value) {
  const finalArray = [];

  for (const item of obj) {
    const matches = item.id.match(/test([234])/);

    if (matches) {
      const testId = matches[1];
      finalArray.push({
        id: item.id,
        value1: `${value}select${testId}1`,
        value2: `${value}select${testId}2`,
      });
    } else {
      finalArray.push({ ...item });
    }
  }

  return finalArray;
}

1 Comment

the values that are shown in the expected output are for illustration. Just to understand better. UPdating it now
0

I have updated your code according to your desire and the snippet is attached just change the values as you like in the function calling. var res1 = updateValue(arrObj,"def");

arrObj = [{ id: "test1", value1: "a1", value2: "b1", }, { id: "test2", value1: "select21", value2: "select22", }, { id: "test3", value1: "select31", value2: "select32", }, { id: "test4", value1: "select41", value2: "select42", } ];

var res1 = updateValue(arrObj,"def");

console.log(res1);

function updateValue(object, value) {
  var newObj = [];
  switch (value) {
      case "abc":
        for (var obj of object){
          if(obj.id != "test1"){
            obj.value1 = value + obj.value1;
            obj.value2 = value + obj.value2;
          }
          newObj.push(obj);
        }
          break;

      case "def":
        for (var obj of object){
          if(obj.id != "test1"){
            obj.value1 = value + obj.value1;
            obj.value2 = value + obj.value2;
          }
          newObj.push(obj);
        }
          break;

      case "ghi":
        for (var obj of object){
          if(obj.id != "test1"){
            obj.value1 = value + obj.value1;
            obj.value2 = value + obj.value2;
          }
          newObj.push(obj);
        }
          break;
  }
  
  return newObj;
}

Comments

0

How about using map function:

var arrObj = [{ id: "test1", value1: "a1", value2: "b1", }, { id: "test2", value1: "a2", value2: "b2", }, { id: "test3", value1: "a3", value2: "b3", }, { id: "test4", value1: "a4", value2: "b4", }],
filters = ['test1', 'test2', 'test4'],
givenValue = 'abc';

result = arrObj.map(({id, ...rest },i)=>{
    if(filters.includes(id)) rest = { value1 : givenValue+'select2'+(i+1), value2 : givenValue+'select2'+(i+1) }
    return {id, ...rest};
});
console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.