我试图在javascript / jquery中组合2个对象数组,用相同的键(代码)匹配它们。这些对象数组存储在2个独立的json文件中。
我已将这些文件删除了
如果有人可以提供帮助,请提前致谢。
对象1:
[{
"code": "abc",
"participant": {
"firstname" : "Joe",
"lastname" : "Blogs"
}
},
{
"code": "def",
"participant": {
"firstname" : "Anna",
"lastname" : "Smith"
}
}]
对象2:
[{
"city": "london",
"selfemployed": {
"job" :"Builder",
"code": "abc",
"participant": {
"firstname" : "Joe",
"lastname" : "Blogs"
}
},
"company" : {
"job": "Shopkeeper",
"code": "def",
"participant": {
"firstname" : "Anna",
"lastname" : "Smith"
}
}
}]
需要的结果:
var file1 = 'url/file1.json';
var file1 = 'url/file2.json';
const joinJson = (file1, file2) => {
$.getJSON(file, function(data1) {
return data1;
});
$.getJSON(file2, function(data2) {
return data2;
});
// do stuff with data1 and data2
}
console.log(joinJson());
我的一个问题是我无法从.json文件中返回该对象
import requests
from bs4 import BeautifulSoup
url = "https://www.reuters.com/finance/stocks/company-officers/MPAPss.BO"
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
table = soup.find('table', {'class': 'dataTable'})
for row in table.find_all("tr")[1::1]:
col = row.find_all("td")
name = col[0].get_text(strip=True)
year = col[2].get_text(strip=True)
position = col[3].get_text(strip=True)
print("Name: {} Year: {} Position: {}".format(name,year,position))
答案 0 :(得分:0)
您可以选择Map
并为结果构建新对象,方法是为新对象选择所需的代码信息。
此提案使用带有babel的对象的rest属性为旧用户代理。
var cities = [{ city: "london", selfemployed: { job: "Builder", code: "abc" }, company: { job: "Shopkeeper", code: "def" } }],
codes = [{ code: "abc", participant: { firstname: "Joe", lastname: "Blogs" } }, { code: "def", participant: { firstname: "Anna", lastname: "Smith" } }],
codesMap = new Map(codes.map(({ code, participant }) => [code, participant])),
result = cities.map(
({ city, ...items }) =>
Object.assign({ city }, ...Object.entries(items).map(
([k, v]) => ({ [k]: Object.assign({}, v, codesMap.get(v.code)) })
))
);
console.log(result);

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

答案 1 :(得分:-1)
问题是你正在异步获取文件,并在异步操作的回调中返回数据,这无处可去。这样的事情会更好:
var file1 = 'url/file1.json';
var file1 = 'url/file2.json';
const joinJson = (file1, file2) => {
$.getJSON(file, function(data1) {
// async operation 1 complete. Start operation 2.
$.getJSON(file2, function(data2) {
// async operation 2 complete
// data1 and data2 are now available here
console.log("Data 1:", data1);
console.log("Data 2:", data2);
// This will merge the keys of both objects
// but you can replace it with custom merging logic
var merged = Object.assign(data1, data2);
console.log(merged);
});
});
}
这里的问题是你不能做console.log(joinJson());
之类的事情。您可能需要类似Promise
的内容。