0

im trying to normalize some data sitting in an array of objects.

[
  {id: 1, number: 10, x: 0.3, y: 0.4, …}
  {id: 2, number: 5, x: 0.5, y: 0.2, …}
  {...}
  {...}
  {...}
]

I want to map the x and y entry's on a new value between 0 - 1250. So I get the following Array of Objects

[
  {id: 1, number: 10, x: 375, y: 500, …}
  {id: 2, number: 5, x: 625, y: 250, …}
  {...}
  {...}
  {...}
]

Whats the best Practice for that?

Best, Chris

1
  • 1
    you can use .map method of array. Commented Jan 17, 2020 at 5:23

3 Answers 3

1

You can use Array.map

const arr = [
  {id: 1, number: 10, x: 0.3, y: 0.4},
  {id: 2, number: 5, x: 0.5, y: 0.2}
];

// Use Array.map to iterate
const arr1 = arr.map(ob => {
  ob.x*=1250; 
  ob.y*=1250; 
  return ob;
});

console.log(arr1);

Sign up to request clarification or add additional context in comments.

2 Comments

The .map is mutating the objects, so it may as well be a .forEach
^ If you do, you can also leave out the return statement.
1

Some thing like this with map method.

const arr = [
  {id: 1, number: 10, x: 0.3, y: 0.4},
  {id: 2, number: 5, x: 0.5, y: 0.2},
];


const res = arr.map(({x, y, ...rest}) => ({...rest, x: x * 1250, y: y * 1250 })); 

console.log(res)

1 Comment

arr.map(obj => Object.assign({}, obj, {x: obj.x * 1250, y: obj.y * 1250})) if you for some reason can't use the object rest spread syntax.
0

Assuming arr is your array of object. You can use map which returns new modified array.

let arr = [
  {
    id: 1, number: 10, x: 0.3, y: 0.4,
  },
  {
    id: 2, number: 5, x: 0.5, y: 0.2
  }
];

const normalize = (obj) => {
  x = obj.x * 1250;
  y = obj.y * 1250;
  return {...obj, x, y};
  // If you're only using mutating then
  // above lines can be
  // obj.x *= 1250;
  // obj.y *= 1250;
  // return obj;
}

// Not mutating array, output new array
const nonMutating = (arr) => {
  let newRes = [];
  arr.forEach(a => {
    newRes.push(normalize(a));
  });
  return newRes;
}

console.log(nonMutating(arr));

console.log("\n");

// Mutating input array
const mutating = (arr) => {
  return arr.map(a => normalize(a));
}

console.log(mutating(arr));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.