我想将一个键数组和一个对象传递给函数,并返回一个仅包含在键数组中指定的键/值对的新对象。
所以,如果我有一个像这样的对象:
{"name" : "John Smith", "position" : "CEO", "year" : "2019" }
我通过了数组
["name", "year"]
返回的新对象将是:
{"name" : "John Smith", "year" : "2019" }
我一直在玩,但我的代码无法正常工作。
function parse(keys, data) {
let obj = JSON.parse(data);
let newObj = {};
keys.array.forEach(element => {
newObj[element] = obj.element;
});
return newObj;
};
答案 0 :(得分:3)
您不需要执行parse
。第二行keys.array.forEach
是错误的。这是因为array
中没有keys
键。也将obj.element;
替换为data[element]
let data = {
"name": "John Smith",
"position": "CEO",
"year": "2019"
}
let keys = ["name", "year"]
function parse(keys, data) {
let newJson = {};
keys.forEach(element => {
newJson[element] = data[element];
});
return newJson;
};
console.log(parse(keys, data))
答案 1 :(得分:2)
一种实现此目的的方法是通过过滤对象条目数组:
const entries = Object.entries({
"name" : "John Smith",
"position" : "CEO",
"year" : "2019"
})
entries
包含:
[
[
"name",
"John Smith"
],
[
"position",
"CEO"
],
[
"year",
"2019"
]
]
过滤键:
const filteredEntries = entries.filter(([ key ]) => ["name", "year"].includes(key))
filteredEntries
包含:
[
[
"name",
"John Smith"
],
[
"year",
"2019"
]
]
最后一步-构造一个对象:
const filteredObject = Object.fromEntries(filteredEntries)
filteredObject
包含:
{
"name": "John Smith",
"year": "2019"
}
将其作为功能组合在一起:
function filterObjectByGivenKeys(object, keys) {
const filteredEntries = Object
.entries(object)
.filter(([ key ]) => keys.includes(key))
return Object.fromEntries(filteredEntries)
}
或者,如果我们更喜欢reduce
和更简洁的语法:
const filterObjectByGivenKeys = (object, keys) =>
Object.entries(object)
.filter(([ key ]) => keys.includes(key))
.reduce((obj, [key, value]) => ({ ...obj, [key]: value }), {})
答案 2 :(得分:2)
完成此操作的正确方法(例如,惰性)将使用lodash
,因为您不编写的代码就是不必维护的代码:
const pick = require('lodash.pick');
const obj = {
name : 'John Smith' ,
position : 'CEO' ,
year : '2019',
};
const desired = [ 'name', 'year' ];
const filtered = pick(obj, desired );
如果您想自己动手,则应采用以下方法:
function filter_obj(obj = {}, keys = [] ) {
if ( !keys || !keys.length ) return obj;
const desired = new Set(keys);
const filtered = {};
for ( [ key, value ] of Object.entries(obj) ) {
if ( !desired.has(key) ) continue;
filtered[key] = value;
}
return filtered;
}
答案 3 :(得分:1)
我认为您的代码很接近。
也许尝试:
newObj[element] = obj[element];
代替
newObj[element] = obj.element
这样,您将使用变量element
而不是尝试查找将返回未定义的键“ element”。
答案 4 :(得分:0)
要获得预期的结果,请使用下面的for in循环对象键选项
var obj = {"name" : "John Smith", "position" : "CEO", "year" : "2019" }
var fil = ["name", "year"]
var result = {}
for(let key in obj){
if(fil.indexOf(key) !==-1){
result[key] = obj[key]
}
}
console.log(result)
答案 5 :(得分:0)
另一种选择是使用reduce方法:
var input = {"name" : "John Smith", "position" : "CEO", "year" : "2019" };
var properties = ["name", "year"];
function getNewObject(json, props) {
// Get all object properties
var availableProperties = Object.keys(json);
// Loop through the requested properties and return the object
return props.reduce((pv, cv) => {
// Check if the property exists on the object
if(availableProperties.includes(cv)){
pv[cv] = json[cv]
}
return pv;
}, {});
}
console.log(getNewObject(input, properties));
答案 6 :(得分:0)
由于您的对象未进行字符串化,因此我删除了上面的对象解析...如果已被字符串化,则“”将包装整个对象...在生产中,您可以根据需要简单地添加解析。
foo inside A!
答案 7 :(得分:0)
您可以使用filter
和对象entries
进行此操作,也可以使用reduce
。
const person = {
"name": "John Smith",
"position": "CEO",
"year": "2019",
"job": "front-end"
};
const formatObject = (arr, o) => {
let finalObject = {};
Object.entries(o).filter(([key, value]) => {
if (arr.includes(key)) {
finalObject = {
...finalObject,
[key]: value
}
}
});
return finalObject;
}
console.log(formatObject(["name", "year", "job"], person))
答案 8 :(得分:0)
首先在单引号内添加以下行{“ name”:“ John Smith”,“ position”:“ CEO”,“ year”:“ 2019”},否则您无需使用JSON.parse:< / p>
'{"name" : "John Smith", "position" : "CEO", "year" : "2019" }'
然后,您不需要数组,只需要键,键。数组 .forEach。 还有obj [element]:
keys.forEach(element => {
newObj[element] = obj[element];
});