假设我有一个对象:

elmo = { 
  color: 'red',
  annoying: true,
  height: 'unknown',
  meta: { one: '1', two: '2'}
};

我想用它的属性子集创建一个新对象。

 // pseudo code
 subset = elmo.slice('color', 'height')

 //=> { color: 'red', height: 'unknown' }

我怎样才能做到呢?


当前回答

还有一个解决方案:

var subset = {
   color: elmo.color,
   height: elmo.height 
}

到目前为止,这看起来比任何答案都更具可读性,但也许这只是我的想法!

其他回答

我认为这就是你的答案。(以及所有正在寻找它的人)。

const object = { a: 5, b: 6, c: 7  };
const subset = (({ a, c }) => ({ a, c }))(object);
console.log(subset); // { a: 5, c: 7 }

我发现最简单的方法,它不会创建不必要的变量,是一个函数,你可以调用,工作原理与lodash相同,如下所示:

pick(obj, keys){
    return  Object.assign({}, ...keys.map(key => ({ [key]: obj[key] })))
}

例如:

pick(obj, keys){
    return  Object.assign({}, ...keys.map(key => ({ [key]: obj[key] })))
}
const obj = {a:1, b:2, c:3, d:4}
const keys = ['a', 'c', 'f']
const picked = pick(obj,keys)
console.log(picked)

Pick = (obj, keys) => { 返回对象。分配({},…键。Map (key => ({ (例子):obj(例子) }))) } Const obj = { 答:1, b: 2 c: 3, d: 4 } Const keys = ['a', 'c', 'f'] Const selected = pick(obj, keys) console.log(选)

你可以使用逗号操作符

const elmo = { 
  color: 'red',
  annoying: true,
  height: 'unknown',
  meta: { one: '1', two: '2'}
};

const subset = ({color , height} = elmo , {color , height});
// {color: 'red', height: 'unknown'}
function splice()
{
    var ret = new Object();

    for(i = 1; i < arguments.length; i++)
        ret[arguments[i]] = arguments[0][arguments[i]];

    return ret;
}

var answer = splice(elmo, "color", "height");

值得注意的是,Zod模式在默认情况下会删除未知属性。如果您已经在使用Zod,那么它很可能适合您的开发过程。

https://github.com/colinhacks/zod

import { z } from "zod";

// muppet schema
const muppet = z.object({
  color: z.string(),
  annoying: z.boolean(),
  height: z.string(),
  meta: z.object({ one: z.string(), two: z.string() }),
});

// TypeScript type if you want it
type TMuppet = z.infer<typeof muppet>;

// elmo example
const elmo: TMuppet = {
  color: "red",
  annoying: true,
  height: "unknown",
  meta: { one: "1", two: "2" },
};

// get a subset of the schema (another schema) if you want
const subset = muppet.pick({ color: true, height: true });

// parsing removes unknown properties by default
subset.parse(elmo); // { color: 'red', height: 'unknown' }