简体   繁体   English

将object.keys从对象数组映射为字符串

[英]map object.keys into string from array of objects

I have an array, this for example: 我有一个数组,例如:

interface: [
    { _id: '1', name: 'Foo' },
    { _id: '2', name: 'bar },
    { _id: '3', name: 'boo}
]

i'd now like to map this to a single string -> 我现在想将此映射到单个字符串->

this.dataSource.data = data.data.map(item => ({
     interface: item.interfaces.name,
}));

so that the result inside the dataSource.data.interface looks like 'Foo, bar, boo' 因此dataSource.data.interface内的结果看起来像'Foo, bar, boo'

You could map the name property and join the array. 您可以映射name属性并加入数组。

 var data = { interface: [{ _id: '1', name: 'Foo' }, { _id: '2', name: 'bar' }, { _id: '3', name: 'boo' }]}; data.interface = data.interface.map(({ name }) => name).join(', '); console.log(data); 

Use Array.prototype.reduce: 使用Array.prototype.reduce:

const concatString = data.interface.reduce((acc, value, index, arr) => {
    const str = index !== arr.length - 1 ? `${value.name}, ` : value.name;
    return acc += str;
    }, "");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用带有Object.keys函数的$ .map从给定Object.keys的数组中获取第一个值? - How can i use $.map with Object.keys function to get the first value from array given for Object.keys? 使用地图遍历对象。 在javascript中过滤,缩小或Object.keys() - Traverse array of objects using map. filter, reduce or Object.keys() in javascript React 将标签添加到 Object.keys 映射中的嵌套数组对象 - React add label to nested array object in Object.keys map 在单个 const 中使用 Object.keys()、map()、...Array()、reduce() 和 concat() - Using Object.keys(), map(), …Array(), reduce() and concat() in a single const 为什么Object.keys返回字符串数组而不是Numbers数组 - Why Object.keys is returns array of string instead of array of Numbers 使用Object.keys将数组错误映射到字符串(javascript) - error mapping array to string with Object.keys (javascript) Object.keys() 数组,其中一个元素被视为字符串? - Object.keys() array with one element treated as string? 映射中的返回Object.keys未定义 - return Object.keys in a map got undefined 为什么 Object.keys(array) 将索引作为字符串返回,而 keys(array) 将它们作为数字返回? - why does Object.keys(array) return the indexes as a string, and keys(array) returns them as numbers? JavaScript Object.keys返回空数组 - JavaScript Object.keys returning empty array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM