Home > Mobile >  Update the object value based on array index
Update the object value based on array index

Time:11-03

I have 2 object in array

dataV[1] = {
            "resolution": "4"
        };

datas[1] = {
     {qty_approved: "1", resolution: "5", status: "", order: "1332"}
}

if both index same then i want to update with the value from 1st. I want to update resolution value to 4 from 5. Based on upcoming value from new array value in dataV

Expected output like this :

datas[1] = {
     {qty_auth: "1", resolution: "4", status: "", order: "1332"}
}

CodePudding user response:

Wherever you're updating the value of dataV you can do something like this, to update the datas:

datas = datas.map((data, i) => {
  return { ...data, resolution: dataV[i].resolution };
});

And if you're using react you can do the same thing in useEffect with dataV as a dependency. So, whenever dataV changes, datas will change automatically.

CodePudding user response:

let array1 = [
    {
        resolution: '4',
    },
];

let array2 = [
    { qty_approved: '1', resolution: '5', status: '', order: '1332' },
];

let array3 = array1.map((element, index) => {
    if (typeof array2[index] != 'undefined') {
        return { ...array2[index], ...element};
    }
    return element;
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

CodePudding user response:

Since you can get the corresponding element by array index, you can get the corresponding resolution as easy as the following snippet:

datas.forEach( (_, i) => {
    datas[i].resolution = dataV[i].resolution
})

CodePudding user response:

  • Using Array#reduce, iterate over dataV while updating a Map where the index is the key and the resolution is the value
  • Using Array#forEach, iterate over datas, if the above map has a key of such index, update the resolution

const 
  dataV = [ { "resolution": "4" }, { "resolution": "7" }, { "resolution": "1" } ],
  datas = [
    { qty_approved: "1", resolution: "5", status: "", order: "1332" },
    { qty_approved: "1", resolution: "3", status: "", order: "1331" },
    { qty_approved: "1", resolution: "9", status: "", order: "1333" },
  ];

const indexResolutionMap = dataV.reduce((map, { resolution }, i) =>
  map.set(i, resolution)
, new Map);

datas.forEach((e, i) => {
  const resolution = indexResolutionMap.get(i);
  if(resolution) e.resolution = resolution;
});

console.log(datas);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The following approach is going to map each item of datas. The mapping function nevertheless will be a real function (not an arrow function), thus it is aware of map's second thisArg argument which for the OP's use case will be the dataV array where one wants to read the resolution values from.

The advantage of such an approach is, that one can work with a reusable mapper function which is agnostic to outside array references because it does process an array while the related/corresponding array gets provided as the mapper functions this context.

The mapping functionality itself does try to not mutate the original item reference by loosely decoupling the reference via creating a shallow copy of the entire item. On top the resolution value which was read from the corresponding array via this[idx].resolution gets assigned to the just created shallow copy.

const datas = [
  { qty_approved: "1", resolution: "5", status: "", order: "1332" },
  { qty_approved: "1", resolution: "3", status: "", order: "1331" },
  { qty_approved: "1", resolution: "9", status: "", order: "1333" },
];

const dataV = [{
  "resolution": "4",
}, {
  "resolution": "7",
}, {
  "resolution": "1",
}];

// mapping approach.

function copyItemAndAssignSameIndexResolutionFromTargetArray(item, idx) {
  // - this merge pattern is agnostic about an `item`'s structure.
  // - `item` could feature more keys but just `resolution` gets reassigned.
  return Object.assign({}, item, { resolution: this[idx].resolution });
}
console.log(
  'mapped version of changed `dataV` items ...',
  datas.map(copyItemAndAssignSameIndexResolutionFromTargetArray, dataV)
);
console.log('still unmutated `datas` ...', { datas });
.as-console-wrapper { min-height: 100%!important; top: 0; }
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

In case the OP wants to mutate each of the datas array's items, the above introduced mapper function changes slightly in order to be utilized by a context aware forEach ...

const datas = [
  { qty_approved: "1", resolution: "5", status: "", order: "1332" },
  { qty_approved: "1", resolution: "3", status: "", order: "1331" },
  { qty_approved: "1", resolution: "9", status: "", order: "1333" },
];

const dataV = [{
  "resolution": "4",
}, {
  "resolution": "7",
}, {
  "resolution": "1",
}];

// mapping approach.

function assignSameIndexResolutionFromTargetArray(item, idx) {
  item.resolution = this[idx].resolution;
  // Object.assign(item, { resolution: this[idx].resolution });
}
datas.forEach(assignSameIndexResolutionFromTargetArray, dataV);

console.log('mutated `datas` array ...', { datas });
.as-console-wrapper { min-height: 100%!important; top: 0; }
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related