本文介绍了返回对象数组的逗号分隔值的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的对象:

I have an object that looks like this:

{
  "id": "123",
   "members": [
     { "id": 1, "name": "Andrew" },
     { "id": 2, "name": "Jim" }
   ]
}

我想要一种返回成员名称字符串的方法:"Andrew, Jim".

I'd like a method to return a string of member names: "Andrew, Jim".

与遍历成员列表并将其添加到数组相反,有没有一种方法可以在一行中干净地完成此操作(也许是underscore.js)?

As opposed to iterating through the member list and adding them to an array, is there a way to accomplish this cleanly in a single line (maybe underscore.js)?

推荐答案

membersObjectsArray,首先您需要创建具有名称的Array-在这种情况下,您可以使用 .map ,然后将其转换为ArrayString-为此,您可以使用 .join

members is Array of Objects, first you need to create Array with names - for this case you can use .map and then convert this Array to String - to do that you can use .join

var data = {
  "id": "123",
   "members": [
     { "id": 1, "name": "Andrew" },
     { "id": 2, "name": "Jim" }
   ]
};

var result = data.members.map(function (e) {
  return e.name;
}).join(', ');

console.log(result);

这篇关于返回对象数组的逗号分隔值的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:35