假设我有一个对象:

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

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

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

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

我怎样才能做到呢?


当前回答

补充另一种深奥的方法,这也很有效:

var obj = {a: 1, b:2, c:3}
var newobj = {a,c}=obj && {a,c}
// {a: 1, c:3}

但是你必须把道具名写两遍。

其他回答

使用对象解构和属性简写

Const对象= {a: 5, b: 6, c: 7}; const = (({a、c }) => ({ a、c}))(对象); console.log(选择);// {a: 5, c: 7}


来自Philipp Kewisch:

这实际上只是一个被即时调用的匿名函数。所有这些都可以在MDN上的解构分配页面上找到。这是一个展开的形式

Let unwrap = ({a, c}) => ({a, c}); 让unwrap2 = function({a, c}){返回{a, c};}; Let selected = unwrap({a: 5, b: 6, c: 7}); 让picke2 = unwrap2({a: 5, b: 6, c: 7}) console.log(选) console.log (picked2)

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' }

Try

const elmo={color:"red",annoying:!0,height:"unknown",meta:{one:"1",two:"2"}};

const {color, height} = elmo; newObject = ({color, height});

console.log(newObject); //{ color: 'red', height: 'unknown' }

我建议看看Lodash;它有很多实用函数。

例如,pick()就是你要找的东西:

var subset = _.pick(elmo, ['color', 'height']);

小提琴