如果检查,ecma6最短循环

时间:2017-11-16 02:11:55

标签: javascript arrays for-loop ecmascript-6

在ecmascript 6中实现此循环的最短方法是什么:

var data = {
        sales: [
            {
                name: "Jim Frost",
                region: "USA East",
                phone: "212-555-1212",
                email: "jfrost@acme-travel.com"
            },
            {
                name: "Jan Smith",
                region: "USA West",
                phone: "310-555-1212",
            }
        ]
};

这是我尝试查看密钥是否等于我的手动设置变量,然后我更改该密钥项的字段,如果没有,我将其更改为其他字段。

var str = '0'; // could also be an integer
for (var key in data.sales) {
  key ===  str ? data.sales[key].region = 'StateChosen' : data.sales[key].region = 'stateEliminated';
}

使用ecma6,object.keys,map,filter,every等方法实现此目的的最短路径是什么?

2 个答案:

答案 0 :(得分:2)

你的例子可以通过以下方式完成:

data.sales.forEach(el => el.region = 'stateEliminated'); // Change every region to eliminated
data.sales[str].region = 'StateChosen'; // Change back the selected to StateChosen.

注意:我假设 str中的data.sales是有效密钥。

答案 1 :(得分:1)

带有解构分配的for of循环和.entries()会有所帮助。

for (let [k, v] of data.sales.entries())
  v.region = k == str ? 'StateChosen' : 'stateEliminated';



var data = {
        sales: [
            {
                name: "Jim Frost",
                region: "USA East",
                phone: "212-555-1212",
                email: "jfrost@acme-travel.com"
            },
            {
                name: "Jan Smith",
                region: "USA West",
                phone: "310-555-1212",
            }
        ]
};
var str = '0';

for (var [k, v] of data.sales.entries())
  v.region = k == str ? 'StateChosen' : 'stateEliminated';

console.log(data);