我试图从一个对象中提取数据并将该数据插入到另一个对象中,但这两个对象具有不同的结构。和它的非常大的物体,超过3000行。
我需要在object1中检查dictionary[0].key.mcp[0]是否存在,如果它存在于object2 conv[0].mcp中,我需要在object1 dictionary[0].dicts中插入4种语言:德语、瑞典语、中文和日语,如果它不存在,则什么也不做
我想也许使用for循环我就能完成任务,但问题是在某些情况下,在键下面,值mcp会为另一个键而改变。
对象1
dictionary = [
{
"key": {
"mcp": [
"mcp.empty"
]
},
"dicts": {
"english": "",
"german": ""
},
"context": null,
"tags": [],
"edited": "2016-10-27T15:41:31.000Z"
},
{
"key": {
"mcp": [
"ui.controls.plasmacontrol.feeder"
]
},
"dicts": {
"english": "Feeder",
"german": "Förderer"
},
"context": null,
"tags": [],
"edited": "2016-10-27T15:41:31.000Z"
},对象2
var conv = [
{
"mcp": "mcp.empty",
"english": "",
"german": "",
"Swedish": "",
"chinese": "",
"japanese": ""
},
{
"mcp": "ui.controls.plasmacontrol.feeder",
"english": "Feeder",
"german": " Förderer ",
"Swedish": "Transportör",
"chinese": "送粉器",
"japanese": "粉末供給装置"
},
{
"mcp": "ui.controls.plasmacontrol.feeder1",
"english": "Feeder 1",
"german": "Förderer 1 ",
"Swedish": "Transportör 1",
"chinese": "1号送粉器",
"japanese": "粉末供給装置1"
},预期的结果是一个将所有数据从object1插入到object2的对象。
对象3(预期结果)
dictionary = [
{
"key": {
"mcp": [
"mcp.empty"
]
},
"dicts": {
"english": "",
"german": "",
"Swedish": "",
"chinese": "",
"japanese": ""
},
"context": null,
"tags": [],
"edited": "2016-10-27T15:41:31.000Z"
},
{
"key": {
"mcp": [
"ui.controls.plasmacontrol.feeder"
]
},
"dicts": {
"english": "Feeder 1",
"german": "Förderer 1 ",
"Swedish": "Transportör 1",
"chinese": "1号送粉器",
"japanese": "粉末供給装置1"
},
"context": null,
"tags": [],
"edited": "2016-10-27T15:41:31.000Z"
},到现在为止,我有这个,并返回了一些错误
import dictionary from "./dictionary.mjs";
import conv from "./converted.mjs";
import _ from "lodash";
import fs from "fs";
import util from 'util';
const newObject = _.map(dictionary, dictionaryItem => {
const key = _.get(dictionaryItem, "key.mcp[0]", "")
const isPresent = _.find(conv, { "mcp": key })
if(isPresent) {
/* console.log('se hizo') */
return { ...dictionaryItem, dicts: {
"english": isPresent.english,
"german": isPresent.german,
"Swedish": isPresent.Swedish,
"chinese": isPresent.chinese,
"japanese": isPresent.japanese
}
}
} else {
/* console.log('no') */
return dictionary
}
})
try {
const data = fs.writeFileSync('./final.js', util.inspect(newObject, {showHidden: false, depth: null}));
//file written successfully
} catch (err) {
console.error(err)
}发布于 2019-08-20 16:53:29
在要执行操作的位置使用lodash First import
import _ from "lodash"
or
const _ = require("lodash")和
const newObject = _.map(dictionary, dictionaryItem => {
const key = _.get(dictionaryItem, "key.mcp[0]", "")
const isPresent = _.find(conv, { "mcp": key })
if(isPresent) {
return { ...dictionaryItem, dicts: {
"english": isPresent.english,
"german": isPresent.german,
"Swedish": isPresent.Swedish,
"chinese": isPresent.chinese,
"japanese": isPresent.japanese
}
}
} else {
return dictionary
}
}) 天哪,你得到你想要的结果了
https://stackoverflow.com/questions/57569165
复制相似问题