0

I have an array of

var imagesArray = [
  {
   url: '4.jpg'
  },
  {
   url: '2.jpg'
  },
  {
   url: '3.jpg'
  }
];

And I got a JSON response of

   [{"path":"site:1.jpg","data":[]},
   {"path":"site:5.jpg","data":[]},
   {"path":"site:7.jpg","data":[]}]

How can I replace the url value in imagesArray from JSON response's path value as 1.jpg, 5.jpg, 7.jpg?

1
  • I don't think what you are asking is clear. What is the relationship? Their position in the array? Ie: does imagesArray[0] == response[0]? Commented Dec 9, 2016 at 7:52

3 Answers 3

2

This will give you an array of three objects with the url property you want.

var formatedResponse = response.map((r) => { return {url: r.path.split(':')[1]};})
Sign up to request clarification or add additional context in comments.

Comments

1
var imagesArray = [
  {
   url: '4.jpg'
  },
  {
   url: '2.jpg'
  },
  {
   url: '3.jpg'
  }
];

response =    [{"path":"site:1.jpg","data":[]},
   {"path":"site:5.jpg","data":[]},
   {"path":"site:7.jpg","data":[]}]

class Test extends React.Component {
        render(){
    imagesArray = imagesArray.map((img,i)=>{return({url : response[i].path}) })
        return (
        <code>{JSON.stringify(imagesArray)}</code>
      )
    }
}

React.render(<Test />, document.getElementById('container'));

DEMO

2 Comments

I need a output as [{"url":"1.jpg"},{"url":"5.jpg"},{"url":"7.jpg"}]
How can I add if response > imagesArray
1

Maybe you can do something like this :

let imagesArray = [
  {
    url: '4.jpg'
  },
  {
    url: '2.jpg'
  },
  {
    url: '3.jpg'
  }
];
    
let response = [
  {"path":"site:1.jpg","data":[]},
  {"path":"site:5.jpg","data":[]},
  {"path":"site:7.jpg","data":[]}
]

let newArray = imagesArray.map( (img, i) => img.url = response.filter( r => r.path)[i]);

console.log(JSON.stringify(newArray));

Here is fiddle.

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.