1

How would I go about returning the key and the value to a string or a smaller object:

 var whatIsInAName = [{ a: "a1", b: "b1" },{ a: "c1", b: "d1" },{ a: "e1", b: "f1" }];

returning something like: "a:a1"

I know about Object.values and Object.keys. Would it be some combination of this?

5
  • 2
    If you don't know the key, and there's no order in objects, how do you get the first one, and does it matter if it's the first one ? Commented Nov 10, 2016 at 17:13
  • 1
    Not certain what expected result is? Commented Nov 10, 2016 at 17:14
  • Object.entries()?...Though I guess it's not official yet. Object.entries({foo:"FOO", bar: "BAR"}); This produces... [["foo","FOO"],["bar","BAR"]] Commented Nov 10, 2016 at 17:15
  • is whatIsInAName supposed to be the name of the function you want to return the key and value? Or is it supposed to be the object var name? Commented Nov 10, 2016 at 17:17
  • @ camiblanch sorry it is supposed to be the object var name Commented Nov 10, 2016 at 17:21

1 Answer 1

3

If interpret Question correctly, you can use Array.prototype.map(), JSON.stringify(), String.prototype.replace() with RegExp /[{}]/g and replacement string "", Array.prototype.join() with parameter ","

var arr = [{ a: "a1", b: "b1" },{ a: "c1", b: "d1" },{ a: "e1", b: "f1" }];

var res = arr.map(obj => JSON.stringify(obj).replace(/[{}]/g,""));

console.log(res.join(","))

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

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.