2

Assuming I have an object array:

array=[
  {
    "Item": "A"
    "Quantity" : 2
  },
  {
    "Item": "B"
    "Quantity" : 7
  },
  {
    "Item": "C"
    "Quantity" : 1
  }
]

I am wondering what would be my options to get the following string output :

(A, 2), (B, 7), (C,1)

4 Answers 4

4

You could map the Object.values and join like this:

  • Loop through the array using map
  • Object.values(a) returns an array like this: ["A", 2]
  • join them using and wrap a () around using template literals
  • join the resulting string array from map using another join

const array = [
  {
    "Item": "A",
    "Quantity" : 2
  },
  {
    "Item": "B",
    "Quantity" : 7
  },
  {
    "Item": "C",
    "Quantity" : 1
  }
]

const str = array.map(a => `(${ Object.values(a).join(", ") })`)
                 .join(", ")
                 
console.log(str)

If you're okay with (A,2), (B,7), (C,1) without a space in between them, you could simply use

const array=[{"Item":"A","Quantity":2},{"Item":"B","Quantity":7},{"Item":"C","Quantity":1}]

const str = array.map(a => `(${ Object.values(a) })`).join(", ")
console.log(str)

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

2 Comments

you need ordered objects and not more properties for this approach.
@NinaScholz You're right. I'm assuming OP has provided MCVE and created the objects in the way it's mentioned in the question :)
3

This is not the most elegant way to do this but it's easy to understand:

array = [{
    "Item": "A",
    "Quantity": 2
  },
  {
    "Item": "B",
    "Quantity": 7
  },
  {
    "Item": "C",
    "Quantity": 1
  }
];

var str = "";
for (var a = 0; a < array.length; a++) {
  str += "(";
  str += array[a].Item + ",";
  str += array[a].Quantity + ")";
  if (a != array.length - 1) {
    str += ",";
  }
}
console.log(str);

Comments

1

You could map the values and join them.

var array = [{ Item: "A", Quantity: 2 }, { Item: "B", Quantity: 7 }, { Item: "C", Quantity: 1 }],
    string = array
        .map(({ Item, Quantity }) => `(${[Item, Quantity].join(', ')})`)
        .join(', ');
    
console.log(string);

Comments

1

You can use

array.map(function(item){ return "(" + item.Item + "," + item.Quantity + ")"}).join(",");

var array=[
  {
    "Item": "A",
    "Quantity" : 2
  },
  {
    "Item": "B",
    "Quantity" : 7
  },
  {
    "Item": "C",
    "Quantity" : 1
  }
];
var result = array.map(function(item){ return "(" + item.Item + "," + item.Quantity + ")"}).join(",");
console.log(result);

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.