Home > Mobile >  Overwrite value of objects in Array by property value
Overwrite value of objects in Array by property value

Time:10-20

I have two arrays of objects. How can i take the property from one array and override the 'value' property of the other array? Currently I'm doing this but it seems quite wonky to do it this way. The original array 'streamingTiles' contains other properties, which is why i have the '...'

Goal is to replace 'value' in streamingTiles with 'counts' value from refTiles based on the matching UID per object

const streamingTiles = [
    {uid: 57, value: 10, ...},
    {uid: 30, value: 51, ...},
    {uid: 14, value: 24, ...},
    {uid: 47, value: 73, ...},
]

const refTiles = [
    {uid: 14, counts: 10},
    {uid: 57, counts: 51},
    {uid: 30, counts: 24},
    {uid: 47, counts: 73},
]

// replace value in streamingTiles with 'count' value from refTiles
const tiles = streamingTiles.map((item) => {
  var refObj = refTiles.find((obj) => {
    return obj.uid === item.uid;
  });

  return { ...item, ...{ value: refObj["counts"] } };
});

CodePudding user response:

Process the refTiles into an object to avoid find calls for each item.

const streamingTiles = [
  { uid: 57, value: 10 },
  { uid: 30, value: 51 },
  { uid: 14, value: 24 },
  { uid: 47, value: 73 },
];

const refTiles = [
  { uid: 14, counts: 10 },
  { uid: 57, counts: 51 },
  { uid: 30, counts: 24 },
  { uid: 47, counts: 73 },
];

const refs = refTiles.reduce(
  (acc, curr) => ((acc[curr.uid] = curr.counts), acc),
  {}
);

const titles = streamingTiles.map((item) => ({
  ...item,
  value: refs[item.uid] ?? item.value,
}));

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

CodePudding user response:

You can just remove the unnecessary object destruction:

const tiles = streamingTiles.map((item) => {
  var refObj = refTiles.find((obj) => {
    return obj.uid === item.uid;
  });

  return { ...item, value: refObj["counts"]};
});
  • Related