仅保留阵列中每个对象中的选定键

时间:2019-02-27 14:20:14

标签: javascript

编辑:不是重复的,因为我的问题不是要删除特定键,而是要在数组中找不到所有键。

在下面,函数redux1keys_to_keep对象中删除与data中未列出的键相对应的条目。

鉴于我有一个要保留的对象键列表,如何才能以一种更简洁的方式重写redux1,而普遍使用mapfilterreduce呢?

var data = [
	{name: 'John', city: 'London', age: 42},
	{name: 'Mike', city: 'Warsaw', age: 18},
	{name: 'Jim', city: 'New York', age: 22},
	{name: 'Celine', city: 'Tokyo', age: 54},
]

var keys_to_keep = ['name', 'city']

function redux1(data) {
	data.forEach((person) => {
		Object.keys(person).forEach((key) => {
			if (!keys_to_keep.includes(key)) {
				delete (person[key])
			}
		})
	})
	console.log(data)
}

function redux2(data) {	
	var reduced = data.filter(person => Object.keys(person).filter(key => keys_to_keep.includes(key)))
	console.log(reduced)
}

redux1(data)
//redux2(data)

我当前的redux2返回对象不会删除age

6 个答案:

答案 0 :(得分:0)

var data = [
	{name: 'John', city: 'London', age: 42},
	{name: 'Mike', city: 'Warsaw', age: 18},
	{name: 'Jim', city: 'New York', age: 22},
	{name: 'Celine', city: 'Tokyo', age: 54},
]

var keys_to_keep = ['name', 'city']

data=data.map(element => Object.assign({}, ...keys_to_keep.map(key => ({[key]: element[key]}))))

console.log(data)

答案 1 :(得分:0)

在其中使用Array.map和Array.forEach:

var data = [
	{name: 'John', city: 'London', age: 42},
	{name: 'Mike', city: 'Warsaw', age: 18},
	{name: 'Jim', city: 'New York', age: 22},
	{name: 'Celine', city: 'Tokyo', age: 54},
]

var keys_to_keep = ['name', 'city']

const result = data.map(e => {
  const obj = {};
  keys_to_keep.forEach(k => obj[k] = e[k])
  return obj;
});

console.log(result);

答案 2 :(得分:0)

您可以结合使用Array#mapArray#reduce

PS > mkdir C:\Temp
PS > dir C:\Temp\
PS > [IO.FileInfo] $foo = 'C:\Temp\foo.txt'
PS > $foo.Exists
False
PS > New-TemporaryFile | Move-Item -Destination C:\Temp\foo.txt
PS > $foo.Refresh()
PS > $foo.Exists
True
PS > $foo | Select-Object *


Mode              : -a----
VersionInfo       : File:             C:\Temp\foo.txt
                    InternalName:
                    OriginalFilename:
                    FileVersion:
                    FileDescription:
                    Product:
                    ProductVersion:
                    Debug:            False
                    Patched:          False
                    PreRelease:       False
                    PrivateBuild:     False
                    SpecialBuild:     False
                    Language:

BaseName          : foo
Target            : {}
LinkType          :
Length            : 0
DirectoryName     : C:\Temp
Directory         : C:\Temp
IsReadOnly        : False
FullName          : C:\Temp\foo.txt
Extension         : .txt
Name              : foo.txt
Exists            : True
CreationTime      : 2/27/2019 8:57:33 AM
CreationTimeUtc   : 2/27/2019 1:57:33 PM
LastAccessTime    : 2/27/2019 8:57:33 AM
LastAccessTimeUtc : 2/27/2019 1:57:33 PM
LastWriteTime     : 2/27/2019 8:57:33 AM
LastWriteTimeUtc  : 2/27/2019 1:57:33 PM
Attributes        : Archive

答案 3 :(得分:0)

data.reduce((r, c) => [ ...r, Object.entries(c).reduce((b, [k, v]) => keys_to_keep.includes(k) ? {...b, [k]: v } : b, {}) ],[])

答案 4 :(得分:0)

比使用 Array#mapObject.fromEntries() 接受的答案略短的版本:

const data = [
    {name: 'John', city: 'London', age: 42},
    {name: 'Mike', city: 'Warsaw', age: 18},
    {name: 'Jim', city: 'New York', age: 22},
    {name: 'Celine', city: 'Tokyo', age: 54},
]

const keys_to_keep = ['name', 'city'];

const redux1 = list => list.map(o => Object.fromEntries(
    keys_to_keep.map(k => [k, o[k]])
));

console.log(redux1(data));

答案 5 :(得分:0)

您可以使用Object.entries

function objfilter(data,keys_to_keep){
    return Object.fromEntries(Object.entries(data).filter(a=>keys_to_keep.includes(a[0])))
}
const data = [
    {name: 'John', city: 'London', age: 42},
    {name: 'Mike', city: 'Warsaw', age: 18},
    {name: 'Jim', city: 'New York', age: 22},
    {name: 'Celine', city: 'Tokyo', age: 54},
]

const keys_to_keep = ['name', 'city'];

console.log(objfilter(data,keys_to_keep))