我从github的api获取信息,但是我不需要一些返回的数据。以下是我用于过滤json数据的代码。 但是,写每个字段太复杂了。有没有更方便的书写方式?
result => {
var obj2 = {
items: []
}
function ObjectCreate(id, tags, score, link, title) {
this.title = title
this.link = link
this.score = score
this.id = id.toString();
this.tags = tags;
}
var need = results.items
for (var i = 0; i < results.items.length; i++) {
var obj = new ObjectCreate(i, need[i].tags, need[i].score, need[i].link, need[i].title);
obj2.items.push(obj);
}
let str = JSON.stringify(obj2, "", "\t")
}
答案 0 :(得分:0)
稍微短一点:
const format = ({ items }) => ({
items: items.map((el, id) => ({ id, title: el.title, link: el.link, score: el.score, tags: el.tags }))
});
或使用一些辅助功能:
const lens = (key, fn) => obj => ({ ...obj, [key]: fn(obj[key]) });
const pick = (...keys) => obj => Object.assign(...keys.map(k => ({ [k]: obj[k] })));
const map = (...fns) => arr => arr.map((el, i) => fns.reduce((el, fn) => fn(el, i), el));
const format = lens("items",
map(
pick("title", "link", "score", "tags"),
(el, index) => el.id = index
)
);
答案 1 :(得分:0)
let data = [{'id':120,'title': 'hello','link': '#', 'score': 24,'tags': 'tags blah blah','location': 'US','price': 120,},{'id':12,'title': 'hello wprld', 'link': '#','score': 125,'tags': 'tags blah blah', 'location': 'SO','price': 12,}
]
const format = data.map( ({id,link,title,score,tags}, index) => ({id:index,link,title,score,tags}))
console.log(format)