在一个数组中访问JSON对象重复值

时间:2018-07-13 15:01:53

标签: json node.js

我要访问'value: '<p>Testing the post</p>',',因此我可以计算字符数并将其返回给用户。我似乎无法访问它。

变量被称为

const links = req.renderData.templateFields

返回对象

 [{ name: 'permalink_slug',
    sqlType: 'VARCHAR',
    sqlDef: '(255)',
    rowTemplate: 'rows/_hidden',
    uiFieldType: 'permalink',
    uiLabel: 'Permalink',
    options: {},
    value: 'http://localhost:3000/posts/testing',
    partial: 'fields/permalink/permalink' },
  { name: 'content',
    sqlType: 'LONGTEXT',
    sqlDef: '',
    rowTemplate: 'rows/_default-row',
    uiFieldType: 'tinymce',
    uiLabel: 'Content',
    options: {},
    value: '<p>Testing the post</p>',
    partial: 'fields/tinymce/tinymce' }]

我尝试过

 for (var i = 0, l = links.length, obj; i < l; i++ )
    {
      obj = links[i];
      links[i] = new Object();
     links[i][obj.name] = obj.value;
      console.log(links[i])
    }

但是这会返回所有名称,并删除我的整个页面,因为它将所有内容变成一个对象

1 个答案:

答案 0 :(得分:0)

假设您的const links = req.renderData.templateFields是对象的以下数组(实际上是数组,而不是问题中提到的对象):

[{
    // ... bla bla
    value: 'http://localhost:3000/posts/testing',
},
{
    // ... bla bla
    value: '<p>Testing the post</p>',
}]

然后,这是如何通过一个属性来增强它的属性,该属性包含每个value属性的字符数(计数):

// Simple way to count the number of letters in a random string,
// see https://stackoverflow.com/a/7349353/1333836 but feel free
// to use any method for calculating the count you prefer.
const countCharacters =
    (str) => str.replace(/[^A-Z]/gi, "").length;

const enhancedWithCount = links.map(link => {
    // for each link, introduce a `count` attribute;
    link.count = countCharacters(link.value);

    return link;
});

// Finally, do res.json(enhancedWithCount)
// or whatever you want with the `enhancedWithCount` array anyways.

enhancedWithCount的外观如下:

[{
    // ... bla bla
    value: 'http://localhost:3000/posts/testing',
    count: 25
},
{
    // ... bla bla
    value: '<p>Testing the post</p>',
    count: 16
}]
相关问题