U
U
ua302021-09-03 14:44:24
JavaScript
ua30, 2021-09-03 14:44:24

How to replace keys or values ​​in an array?

Good afternoon!

There is such an array object (I don’t know exactly how to call it correctly):

{"key":
  [
    {"id":"key","data_1":"data1","data2":"data2"},
    {"id":"key","data_1":"data1","data2":"data2"},
    {"id":"key","data_1":"data1","data2":"data2"},
  ]
}


I need to replace all data_1 keys with data_2 in it (and data_2 with data_1, respectively). Well, OR replace all values ​​of data1 with data2 (and vice versa) - it does not change the essence, which will be more beautiful and more productive. Performance is critical - everything is spinning in the client's browser, the largest array weighs just over 1 mb, not a little ...

Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
WapSter, 2021-09-03
@wapster92

const obj = {"key":
  [
    {"id":"key","data_1":"data1","data2":"data2"},
    {"id":"key","data_1":"data1","data2":"data2"},
    {"id":"key","data_1":"data1","data2":"data2"},
  ]
}

const arr = obj.key.map(n => ({...n, data_1: n.data2, data2: n.data_1}))

D
dollar, 2021-09-03
@dollar

The fastest way is not to create new arrays and objects, but to go through a loop. Ideally, do not even call functions.

let obj = {"key":
  [
    {"id":"key","data_1":"data1","data_2":"data2"},
    {"id":"key","data_1":"data1","data_2":"data2"},
    {"id":"key","data_1":"data1","data_2":"data2"},
  ]
};

let arr = obj.key;
for (let i=arr.length-1; i>=0; i--) {
  let item = arr[i];
  let t = item.data_1
  item.data_1 = item.data_2
  item.data_2 = t
}

In essence, the question is how to swap variables xand yplaces:
let temp = x
x = y
y = temp

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question