-2
newDesign = {
    color: 'blue',
    shape: 'round'
}

oldDesign = {
    color: 'yellow',
    shape: 'triangle'
}

I want to compare this two design to see if their field is changed, so I write these:

fields = [ 'color', 'shape' ]
for (let field in fields) {
    if (oldDesign.field !== newDesign.field)
        console.log('changed')
}

However, looks like I can't read the value of fields by using oldDesign.field.

Is there a way to to this? Thank you.

ilikechocolate
  • 193
  • 1
  • 12
  • 1
    Don't use `for..in` to loop arrays [Why is using “for…in” with array iteration a bad idea?](https://stackoverflow.com/questions/500504) – adiga Feb 23 '19 at 20:21
  • 1
    Use a `for` loop or `forEach` like this: `fields.forEach(field =>{ if (oldDesign[field] !== newDesign[field]) console.log('changed') })` – adiga Feb 23 '19 at 20:27

1 Answers1

0

Use the bracket notation

var newDesign = {
    color: 'blue',
    shape: 'round'
}

var oldDesign = {
    color: 'yellow',
    shape: 'triangle'
}

var fields = [ 'color', 'shape' ];
for (let field in fields) {
    if (oldDesign[fields[field]] != newDesign[fields[field]])
        console.log('changed')
}
ellipsis
  • 12,049
  • 2
  • 17
  • 33