繁体   English   中英

对象数组的算术运算-JavaScript

[英]Arithmetic operations on array of objects - JavaScript

我有一个JSON

const myJSON = [
    {
        name: 'compass',
        LocX: 35,
        LocY: 312
    },
    {
        name: 'another',
        LocX: 52,
        LocY: 32
    }
]

在用户界面中,如果用户想在两个属性之一中添加数字5,该如何处理?

我已经在做

myJSON.map(x => x[userSelectedProperty] + 5)
// when user selected property is 'LocX', [40, 57]

但我想只更新值的完整数组。

[
    {
        name: 'compass',
        LocX: 40,
        LocY: 312
    },
    {
        name: 'another',
        LocX: 57,
        LocY: 32
    }
]

我该怎么做呢?

只需使用Array#forEcah方法迭代并更新对象属性Array#forEcah ,这足以满足此目的。

 const myJSON = [{ name: 'compass', LocX: 35, LocY: 312 }, { name: 'another', LocX: 52, LocY: 32 } ]; let userSelectedProperty = 'LocX'; myJSON.forEach(x => x[userSelectedProperty] += 5); console.log(myJSON); 


如果要创建一个新数组,请使用Array#map方法。

 const myJSON = [{ name: 'compass', LocX: 35, LocY: 312 }, { name: 'another', LocX: 52, LocY: 32 } ]; let userSelectedProperty = 'LocX'; let res = myJSON.map(x => { // copy properties to a new object let y = Object.assign({}, x); y[userSelectedProperty] += 5; return y; }); console.log(res); 

您可以只在数组上使用.forEach循环来更新其中的属性,而不用创建新的数组。

 const myJSON = [ { name: 'compass', LocX: 35, LocY: 312 }, { name: 'another', LocX: 52, LocY: 32 } ]; var userSelectedProperty = "LocX"; // Update the array. myJSON.forEach(t => t[userSelectedProperty] += 5); console.log(myJSON); 

不需要map使用forEach并更新键值

 const myJSON = [{ name: 'compass', LocX: 35, LocY: 312 }, { name: 'another', LocX: 52, LocY: 32 } ] function addNum(key, val) { myJSON.forEach(function(item) { item[key] = item[key] + val; }) } addNum('LocX', 5) console.log(myJSON) 

使用Object.assign可以轻松做到这一点

 const myJSON = [ { name: 'compass', LocX: 35, LocY: 312 }, { name: 'another', LocX: 52, LocY: 32 } ] let userSelectedProperty = 'LocX'; let newObject = myJSON.map(x => Object.assign({}, x, {[userSelectedProperty]: x[userSelectedProperty] + 5})); console.log(newObject); 

请尝试以下操作:

 const myJSON = [ { name: 'compass', LocX: 35, LocY: 312 }, { name: 'another', LocX: 52, LocY: 32 } ] var userInput = 5; var final = myJSON.map((x, i)=>{ return {name:x.name ,LocX:x.LocX+userInput, LocY:x.LocY}; }); console.log(final); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM