Q:

Create new array of objects based on data from a filtered array of objects

I have an array of objects with a key called 'selected' which is set to false. I have a filtered array of objects from the original list where the key 'selected' is set to true. How do I create a new array where the original list is updated with true values based on the filtered list?

const data = [{
    color: "red",
    value: "#f00",
    selected: false
  },
  {
    color: "green",
    value: "#0f0",
    selected: false
  },
  {
    color: "blue",
    value: "#00f",
    selected: false
  },
  {
    color: "cyan",
    value: "#0ff",
    selected: false
  },
  {
    color: "magenta",
    value: "#f0f",
    selected: false
  },
  {
    color: "yellow",
    value: "#ff0",
    selected: false
  },
  {
    color: "black",
    value: "#000",
    selected: false
  }
]

const filtered = [{
  color: "magenta",
  value: "#f0f",
  selected: true
}, {
  color: "green",
  value: "#0f0",
  selected: true
}, {
  color: "black",
  value: "#000",
  selected: true
}]

const newData = data.map(item => {
  item.selected = filtered.find(item1 => item1.id === item.id).selected
  return item
})

console.log(newData)

The end result should be
    [{
        color: "red",
        value: "#f00",
        selected: false
      },
      {
        color: "green",
        value: "#0f0",
        selected: **true**
      },
      {
        color: "blue",
        value: "#00f",
        selected: false
      },
      {
        color: "cyan",
        value: "#0ff",
        selected: false
      },
      {
        color: "magenta",
        value: "#f0f",
        selected: **true**
      },
      {
        color: "yellow",
        value: "#ff0",
        selected: false
      },
      {
        color: "black",
        value: "#000",
        selected: **true**
      }
    ]

A:

You need to check color property and return a new object with a change of the property if an object is found.

const 
    data = [{ color: "red", value: "#f00", selected: false }, { color: "green", value: "#0f0", selected: false }, { color: "blue", value: "#00f", selected: false }, { color: "cyan", value: "#0ff", selected: false }, { color: "magenta", value: "#f0f", selected: false }, { color: "yellow", value: "#ff0", selected: false }, { color: "black", value: "#000", selected: false }],
    filtered = [{ color: "magenta", value: "#f0f", selected: true }, { color: "green", value: "#0f0", selected: true }, { color: "black", value: "#000", selected: true }],
    newData = data.map(item => {
        var object = filtered.find(item1 => item1.color === item.color);
        return Object.assign({}, item, object && { selected: object.selected });
    });

console.log(newData)
.as-console-wrapper { max-height: 100% !important; top: 0; }

