将嵌套数组的第一个元素指定为父对象的属性

时间:2017-07-11 15:24:26

标签: javascript ecmascript-6 lodash

假设以下数组:

[
{id: 1234, name: "@Acme", sources:["Twitter"]},
{id: 5678, name: "@Enron", sources:["Facebook"]},
]

我想将sources[0]提升为属性值,可以是源代码本身,也可以是lodash的新密钥。

我做了以下事情:

myList = _.map(monitorList, _.partialRight(_.pick, ['id', 'name', 'sources']));
mySources = _.map(monitorList, 'sources');

我想我现在可以遍历每个相应的数组并将我的索引从mySources映射到myList中的sources键,但是看起来应该有一种使用lodash来提升嵌套的功能方式数组项到属性值。

理想的最终数据结构:

[
{id: 1234, name: "@Acme", sources:"Twitter"},
{id: 5678, name: "@Enron", sources:"Facebook"},
]

3 个答案:

答案 0 :(得分:2)

使用功能强大的ES6方法:

const monitorList = [
    {id: 1234, name: "@Acme", sources:["Twitter"]},
    {id: 5678, name: "@Enron", sources:["Facebook"]},
];

var result = monitorList.map(o => Object.assign({}, o, { sources: o.sources[0] }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

您可以按照简单的路径使用forEach替换sources属性:

var items = [{id: 1234, name: "@Acme", sources:["Twitter"]},
             {id: 5678, name: "@Enron", sources:["Facebook"]}];

items.forEach((item) => item.sources = item.sources[0]);

console.log(items);

使用map的另一个解决方案,它更具功能性(因为它不会更改items变量):

var items = [{id: 1234, name: "@Acme", sources:["Twitter"]},
             {id: 5678, name: "@Enron", sources:["Facebook"]}];

var newItems = items.map((item) => Object.assign({}, item, { sources: item.sources[0] }));

console.log(newItems);

答案 2 :(得分:1)

你可以使用map:

$qu3 = 'UPDATE logs SET out= '.date("Y-m-d H:i:s").' WHERE sl_no= '.$sno;

  $r4 = mysql_query($qu3)or die(mysql_error());

如果要覆盖,也可以将item.source更改为item.sources。

使用一些losdash方法的另一种方法:

<table>

<td class="amount balance">
    <input type="number" class="form-control" placeholder="balance" ng-model="total_balance" />
</td>
<td class="amount debit">
    <input type="number" class="form-control" placeholder="debit"  ng-model="amount_debit" />
</td>
<td class="amount credit">
    <input type="number" class="form-control" placeholder="credit"  ng-model="amount_credit">
</td>
<td class="amount balance" ng-class="{
    negative : (total_balance - amount_debit + amount_credit) < 0.00, 
    positive : (total_balance - amount_debit + amount_credit) >= 0.00
}">
    @{{total_balance - amount_debit + amount_credit | currency:""}}
</td>

</table>