1

I am trying to replace / change the values in an object, but I can't seem to work out how it's done or if it can even be done.

I'm trying to add https://SiteName.com to the start of each of the values so it will be like https://SiteName.com\/asset\/image\/map\/map-grass.svg

var assets = [{
  "name": "\/asset\/image\/map\/map-grass.svg",
  "url": "\/asset\/image\/map\/map-grass.svg"
}, {
  "name": "\/asset\/image\/map\/map-stone.svg",
  "url": "\/asset\/image\/map\/map-stone.svg"
}]

Object.keys(assets).forEach(key => {
  const val = assets[key];
  console.log(val)
});

2 Answers 2

2

Try this:

var assets = [{
  "name": "\/asset\/image\/map\/map-grass.svg",
  "url": "\/asset\/image\/map\/map-grass.svg"
}, {
  "name": "\/asset\/image\/map\/map-stone.svg",
  "url": "\/asset\/image\/map\/map-stone.svg"
}]

let url = "https://SiteName.com";

Object.keys(assets).forEach(key => {
  const val = assets[key];
  val.name = url + val.name;
  val.url = url + val.url;
});

console.log(assets)

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

1 Comment

What's the point of using the Object.keys method on an array? Just use forEach.
2

You need a nested loop (or forEach) here - one to go over the elements of the assets array, and then, for each object in there, go over all its properties:

var assets = [{
  "name": "\/asset\/image\/map\/map-grass.svg",
  "url": "\/asset\/image\/map\/map-grass.svg"
}, {
  "name": "\/asset\/image\/map\/map-stone.svg",
  "url": "\/asset\/image\/map\/map-stone.svg"
}]

assets.forEach(o => {
    Object.keys(o).forEach(key => {
      o[key] = 'https://SiteName.com' + o[key];
    })
});

console.log(assets);

Comments

Your Answer

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