分解任意对象属性

时间:2019-08-09 07:38:20

标签: javascript arrays object object-destructuring

有没有办法将对象分解为任意属性值和其余属性?

到目前为止,我的尝试并没有取得太大成功:

const x = {a:1, b:2, c:3};
const obj2pieces = (obj,propName) => {
    ({propName,...rest} = obj);
    return [propName, {...rest}]
};
console.log(obj2pieces(x, 'a')); // [undefined,{"a":1,"b":2,"c":3}]

我想得到的是[1,{"b":2,"c":3}]

1 个答案:

答案 0 :(得分:0)

您需要computed property name和重命名提取值。

const
    x = { a: 1, b: 2, c: 3},
    obj2pieces = (obj, propName) => {
        const {[propName]: temp, ...rest } = obj;
        return [temp, rest]
    };

console.log(obj2pieces(x, 'a'));