0

i'm new to es6 and i have an array of objects like below:

checkProps = [ {symbol: rwerwe}, {side: Buy}, {status: Hey} ]

With a for loop i want to create a string like: myurl = localhost:3000/symbol=rwerwe&side=Buy&status=Hey

For this i have to get access to the keys of each object and use concat for the string composition. I used Object.keys but it returns integers. I want something to return the symbol, side and status. How to do this?

2 Answers 2

2

Please try this:

var checkProps = [ {symbol: 'rwerwe'}, {side: 'Buy'}, {status: 'Hey'} ];
var urlStr = 'localhost:3000/';
var urlParams = [];
checkProps.forEach(function(o) {
  var keys = Object.keys(o);
  keys.map(function(key) {
      urlParams.push(key + '=' + o[key])
  });
});

urlStr += urlParams.join('&');
console.log(urlStr)

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

1 Comment

Awesome! Thanks a lot :)
0

You need to loop over the array and apply Object.keys to the items.

const parameters = checkProps.map(item => Object.keys(item).map(key => key + "=" + item[key])[0])
                             .join("&");
const myUrl = `localhost:3000/${parameters}`;

It's a bit cleaner with ES2017 and Object.entries:

const parameters = checkProps.map(item => Object.entries(item)[0])
                             .map(parameter => parameter.join("="))
                             .join("&");

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.