user13349816
user13349816

Reputation:

Find and replace required object properties with values with respect to array of objects

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;
}

Upvotes: 1

Views: 423

Answers (5)

Rajneesh
Rajneesh

Reputation: 5308

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);

Upvotes: 0

Mulan
Mulan

Reputation: 135257

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)

Upvotes: 1

Abdul Moeez
Abdul Moeez

Reputation: 1401

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;
}

Upvotes: 0

Mehmet Baker
Mehmet Baker

Reputation: 1155

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;
}

Upvotes: 0

Luciano
Luciano

Reputation: 475

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

Upvotes: 0

Related Questions