[英]Add key and value to array of objects object from the keys in array
我有一個對象數組:
let json = [
{cat: 'one', device: 'iphone', site: 'google', val1:10, val2:20, val3:30},
{cat: 'two', device: 'iphone', site: 'bing', val1:23, val2:12, val3:14},
{cat: 'three', device: 'iphone', site: 'jeeves', val1:67, val2:78, val3:12},
{cat: 'four', device: 'ipad', site: 'google', val1:10, val2:20, val3:30},
{cat: 'five', device: 'ipad', site: 'bing', val1:23, val2:12, val3:14},
{cat: 'six', device: 'ipad', site: 'jeeves', val1:67, val2:78, val3:12},
{cat: 'seven', device: 'mac', site: 'google', val1:10, val2:20, val3:30},
{cat: 'eight', device: 'mac', site: 'bing', val1:23, val2:12, val3:14},
{cat: 'nine', device: 'mac', site: 'jeeves', val1:67, val2:78, val3:15}
]
然后我有一個數組: arr = ['device', 'object']
我有一個 object:
obj= {
a: 'one',
}
我想將數組中的任何內容(在本例中為['device', 'object']
)添加到 obj.
在上面的例子中,我希望 obj 看起來像這些對象數組:
[
{
a: 'one',
device: 'iphone'
object: 'google'
},
{
a: 'two',
device: 'iphone'
object: 'bing'
},
{
a: 'three',
device: 'iphone'
object: 'jeeves'
},
.........
]
鍵數組(arr)可能不同,因此不確定如何編寫可重用的 function。
如果我理解你的話,你可以這樣做。 我假設您json
和obj
已排序並具有相同的列表,否則您還需要通過cat
進行搜索以在json
中找到正確的行
const json = [ {cat: 'one', device: 'iphone', site: 'google', val1:10, val2:20, val3:30}, {cat: 'two', device: 'iphone', site: 'bing', val1:23, val2:12, val3:14}, {cat: 'three', device: 'iphone', site: 'jeeves', val1:67, val2:78, val3:12}, ] const objs = [ { a: 'one', }, { a: 'two', }, { a: 'three', }, ] const arr = ['device', 'site'] const result = objs.map((obj, i) => { arr.forEach(key => { obj[key] = json[i][key] }) return obj }) console.log(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.