��权限没有,则隐藏 function forum_list_access_filter($forumlist, $gid, $allow = 'allowread') { global $grouplist; if (empty($forumlist)) return array(); if (1 == $gid) return $forumlist; $forumlist_filter = $forumlist; $group = $grouplist[$gid]; foreach ($forumlist_filter as $fid => $forum) { if (empty($forum['accesson']) && empty($group[$allow]) || !empty($forum['accesson']) && empty($forum['accesslist'][$gid][$allow])) { unset($forumlist_filter[$fid]); } unset($forumlist_filter[$fid]['accesslist']); } return $forumlist_filter; } function forum_filter_moduid($moduids) { $moduids = trim($moduids); if (empty($moduids)) return ''; $arr = explode(',', $moduids); $r = array(); foreach ($arr as $_uid) { $_uid = intval($_uid); $_user = user_read($_uid); if (empty($_user)) continue; if ($_user['gid'] > 4) continue; $r[] = $_uid; } return implode(',', $r); } function forum_safe_info($forum) { //unset($forum['moduids']); return $forum; } function forum_filter($forumlist) { foreach ($forumlist as &$val) { unset($val['brief'], $val['announcement'], $val['seo_title'], $val['seo_keywords'], $val['create_date_fmt'], $val['icon_url'], $val['modlist']); } return $forumlist; } function forum_format_url($forum) { global $conf; if (0 == $forum['category']) { // 列表URL $url = url('list-' . $forum['fid'], '', FALSE); } elseif (1 == $forum['category']) { // 频道 $url = url('category-' . $forum['fid'], '', FALSE); } elseif (2 == $forum['category']) { // 单页 $url = url('read-' . trim($forum['brief']), '', FALSE); } if ($conf['url_rewrite_on'] > 1 && $forum['well_alias']) { if (0 == $forum['category'] || 1 == $forum['category']) { $url = url($forum['well_alias'], '', FALSE); } elseif (2 == $forum['category']) { // 单页 $url = ($forum['threads'] && $forum['brief']) ? url($forum['well_alias'] . '-' . trim($forum['brief']), '', FALSE) : url($forum['well_alias'], '', FALSE); } } return $url; } function well_forum_alias() { $forumlist = forum_list_cache(); if (empty($forumlist)) return ''; $key = 'forum-alias'; static $cache = array(); if (isset($cache[$key])) return $cache[$key]; $cache[$key] = array(); foreach ($forumlist as $val) { if ($val['well_alias']) $cache[$key][$val['fid']] = $val['well_alias']; } return array_flip($cache[$key]); } function well_forum_alias_cache() { global $conf; $key = 'forum-alias-cache'; static $cache = array(); // 用静态变量只能在当前 request 生命周期缓存,跨进程需要再加一层缓存:redis/memcached/xcache/apc if (isset($cache[$key])) return $cache[$key]; if ('mysql' == $conf['cache']['type']) { $arr = well_forum_alias(); } else { $arr = cache_get($key); if (NULL === $arr) { $arr = well_forum_alias(); !empty($arr) AND cache_set($key, $arr); } } $cache[$key] = empty($arr) ? '' : $arr; return $cache[$key]; } ?>javascript - Array.reduce() on an array of objects -- getting back strings of single letters - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Array.reduce() on an array of objects -- getting back strings of single letters - Stack Overflow

programmeradmin4浏览0评论

I'm working to understand Array.reduce() in JavaScript. I have an array of objects that I'm trying to apply .reduce() to, but I'm getting back an array of single letter strings.

Goal:

["Stuff", "necklace", "ring", "bracelet"]

Current Array of Objects

const productArray =
[
    {
        id: 1,
        productTitle: "Necklace"
    },
    {
        id: 2,
        productTitle: "Ring"
    },
    {
        id: 3,
        productTitle: "Bracelet"
    }
]

Function call

const newStuff = productArray.reduce(function(a, currentValue) {
    return [...a, ...currentValue.productTitle];
}, ["Stuff"])

Actual result:

What do I need to do to specify that I don't want "productTitle" broken down into single-letter strings? I have been looking for resources regarding .reduce() on an array of objects but I haven't found anything very helpful. Any pointers?

I'm working to understand Array.reduce() in JavaScript. I have an array of objects that I'm trying to apply .reduce() to, but I'm getting back an array of single letter strings.

Goal:

["Stuff", "necklace", "ring", "bracelet"]

Current Array of Objects

const productArray =
[
    {
        id: 1,
        productTitle: "Necklace"
    },
    {
        id: 2,
        productTitle: "Ring"
    },
    {
        id: 3,
        productTitle: "Bracelet"
    }
]

Function call

const newStuff = productArray.reduce(function(a, currentValue) {
    return [...a, ...currentValue.productTitle];
}, ["Stuff"])

Actual result:

What do I need to do to specify that I don't want "productTitle" broken down into single-letter strings? I have been looking for resources regarding .reduce() on an array of objects but I haven't found anything very helpful. Any pointers?

Share Improve this question edited Apr 4, 2018 at 11:09 Ben Watson 5,5516 gold badges43 silver badges71 bronze badges asked Apr 3, 2018 at 20:40 Leia_OrganaLeia_Organa 2,1047 gold badges34 silver badges58 bronze badges 1
  • Don't post images, post your code as a runnable snippet. – RobG Commented Apr 3, 2018 at 20:47
Add a ment  | 

5 Answers 5

Reset to default 5

To concatenate an array and value when using spread to create a new array, you spread the previous array to the new array, and add the new item without spreading it.

const productArray = [{"id":1,"productTitle":"Necklace"},{"id":2,"productTitle":"Ring"},{"id":3,"productTitle":"Bracelet"}];

const newStuff = productArray.reduce((a, currentValue) => 
  [...a, currentValue.productTitle], []);

console.log(newStuff);

In this case, it's better to use Array.map():

const productArray = [{"id":1,"productTitle":"Necklace"},{"id":2,"productTitle":"Ring"},{"id":3,"productTitle":"Bracelet"}];

const newStuff = productArray.map((currentValue) => currentValue.productTitle);

console.log(newStuff);

Do not spread the title, pass it as it is:

const newStuff = productArray.reduce(function(a, currentValue) {
  return [...a, currentValue.productTitle];
}, ["Stuff"]);

...currentValue.productTitle spreads into an array of individual letters, you only want to spread a variable, the aggregate here.

Basically a string is iterable, because the iterator is implemented and returns an array of single characters, if using spread syntax ....

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

console.log([...'foo']);

Other answers have pointed out why your code is wrong. But I do want to also note that what you're doing is already covered by Array.prototype.concat:

const productArray = [{"id":1,"productTitle":"Necklace"},{"id":2,"productTitle":"Ring"},{"id":3,"productTitle":"Bracelet"}];

const newStuff = productArray.reduce((a, val) => a.concat(val.productTitle), ['Struff']);
console.log(newStuff);

(And of course, as another answer has mentioned, this sounds more like a use for map than reduce, which might not matter since you're using this to learn reduce.)

The use of spread in this case is unnecessary and inefficient as it creates a new accumulator array from the previous one on every iteration. You can remove spread (and fix your issue) and use concat instead to keep it as a one-liner.

However, since you're just adding one new value on each iteration, you should use push. It requires one more line of code but is likely more efficient than using concat.

var productArray = [{id: 1,productTitle: "Necklace"},
                    {id: 2,productTitle: "Ring"},
                    {id: 3,productTitle: "Bracelet"}
];

// Using concat
var newStuff = productArray.reduce((acc, value) =>
  acc.concat(value.productTitle),
["Stuff"]);

console.log(newStuff);

// Using push
var newStuff = productArray.reduce((acc, value) => {
  acc.push(value.productTitle);
  return acc;
}, ["Stuff"]);

console.log(newStuff);

发布评论

评论列表(0)

  1. 暂无评论