将数组映射到由数组值作为键的对象

时间:2018-08-09 12:46:37

标签: javascript arrays object mapreduce

我需要能够根据数组值从对象中删除对象。

我有一个基础对象:

   const obj = {
      one: {
        selected: undefined,
      }, 
      two: {
        selected: undefined,
      },
      three: {
        selected: undefined,
      }
    };

示例数组为:

const arr = ['one', 'two'];

我这样做的尝试:

const mappedObj = arr.map(val => {
  if (obj[val]) {
    return ({
      [val]: {
        selected: true
      },
    });
  }

  return false;
})

我需要这样:

object: {
  one: {
    selected: true,
  },
  two: {
   selected: true,
  }
}

6 个答案:

答案 0 :(得分:1)

您可以映射单个对象,并将其分配给数组为Object.assignspread syntax ...的单个对象。

var object = { one: { selected: undefined, foo: 42 }, two: { selected: undefined }, three: { selected: undefined } },
    array = ['one', 'two'],
    result = Object.assign(
        ...array.map(k => ({ [k]: Object.assign({}, object[k], { selected: true }) }))
    );
  
console.log(result);

答案 1 :(得分:0)

您可以在reduce数组上使用arr

const result = arr.reduce((acc, key) => {
  if (obj[key]) {
    acc[key] = { ...obj[key], selected: true };
  }
  return acc
}, {});

答案 2 :(得分:0)

您可以使用简单的forEach()循环:

const obj = {
      one: {
        selected: undefined,
      }, 
      two: {
        selected: undefined,
      },
      three: {
        selected: undefined,
      }
    };

const arr = ['one', 'two'];
Object.keys(obj).forEach((key) => obj[key].selected = arr.includes(key));
console.log(obj);

答案 3 :(得分:0)

您可以使用“ reduce”代替“ map”:

const obj = {
      one: {
        selected: undefined,
      }, 
      two: {
        selected: undefined,
      },
      three: {
        selected: undefined,
      }
    };
const arr = ['one', 'two'];
const mappedObj = arr.reduce((acm, val) => { 
    if (val in obj) { 
      acm[val] = { selected: true };
    }
    return acm;
  }, 
  {}
);

结果:

{ one: { selected: true }, two: { selected: true } }

答案 4 :(得分:0)

const obj = {
      one: {
        selected: undefined,
      }, 
      two: {
        selected: undefined,
      },
      three: {
        selected: undefined,
      }
    };

const arr = ['one', 'two'];

Object.keys(obj).map((item) => { 
       if(arr.includes(item)){
         obj[item].selected = true
       } else { 
        delete obj[item]
       }
     })

 console.log(obj)

答案 5 :(得分:0)

使用一行reduce()

const obj = {
      one: {
        selected: undefined,
      }, 
      two: {
        selected: undefined,
      },
      three: {
        selected: undefined,
      }
    };



const arr = ['one', 'two'];



const res = 
   arr.reduce((a,c) => (obj[c] && (a[c]= Object.assign({}, obj[c], {selected:true})),a),{});
 

console.log(res)