使用选择的项目创建新对象

时间:2018-03-08 16:56:45

标签: javascript arrays object variables

myObject  { orange: "10.5", banana:"20.5", apple: "5.1", pineapple: "5.1", cherry: "5.1" }

我想创建这个

myNewObject { apple: "5.1", cherry: "5.1" }

我的代码是

for (var property in myObject)  {
delete object["orange"];
delete object["banana"];
delete object["pineapple"];
}

) 是否有与删除功能相反的功能?我想在数组中声明我保留在myNewObject中的项目选择

var FruitsRed = ["apple", "cherry",]

6 个答案:

答案 0 :(得分:1)

您可以创建所需属性的数组,并使用.map()创建对象列表,然后将其传递给Object.assign()



var myObject = {orange: "10.5", banana: "20.5", apple: "5.1", pineapple: "5.1", cherry: "5.1"};

var res = Object.assign({}, 
   ...["banana", "cherry"].map(s => ({[s]: myObject[s]}))
);

console.log(res);




或者,如果你真的想要 mutate 原始对象,就像你的第一个例子一样,那么你可以迭代所有的键并删除那些不在前面的键。定义集。



var myObject = {orange: "10.5", banana: "20.5", apple: "5.1", pineapple: "5.1", cherry: "5.1"};
var toKeep = new Set(["banana", "cherry"]);

Object.keys(myObject)
      .filter(k => !toKeep.has(k))
      .forEach(k => delete myObject[k]);

console.log(myObject);




答案 1 :(得分:1)

您可以使用filterincludesreduce这些功能。

var FruitsRed = ["apple", "cherry"],
    myObject = { orange: "10.5", banana:"20.5", apple: "5.1", pineapple: "5.1", cherry: "5.1" },
    myNewObject = Object.keys(myObject)
                        .filter(k => FruitsRed.includes(k))
                        .reduce((a, k) => ({ ...a, ...{[k]: myObject[k]}}), {});


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

答案 2 :(得分:1)

或者您可以使用对象ES6解构。



let myObject = { orange: "10.5", banana:"20.5", apple: "5.1", pineapple: "5.1", cherry: "5.1" };

let { orange, banana, pineapple, ...myNewObject } = myObject;
console.log(myNewObject);




Doc:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

答案 3 :(得分:0)

您可以循环遍历数组并随时构建新对象。

var obj = { orange: "10.5", banana:"20.5", apple: "5.1", pineapple: "5.1", cherry: "5.1" }
    
var FruitsRed = ["apple", "cherry",]
var newObj = {}
FruitsRed.forEach(function (fruit) {
    newObj[fruit] = obj[fruit];
});
console.log(newObj);

答案 4 :(得分:0)

您可以遍历数组并获得所需的键值对:

var myObject = { "orange": "10.5", "banana":"20.5", "apple": "5.1", "pineapple": "5.1", "cherry": "5.1" };
var myNewObject = {};
var FruitsRed = ["apple", "cherry"];

FruitsRed.forEach(function(fruit){
   myNewObject[fruit] = myObject[fruit];
});

console.log(myNewObject);

答案 5 :(得分:0)

class

让我知道这是否有效