gpt4 book ai didi

javascript - 如何仅从 json 根属性获取非数组值

转载 作者:行者123 更新时间:2023-12-04 00:06:34 27 4
gpt4 key购买 nike

如何以编程方式仅从 Javascript 中的 JSON 对象的根中获取非数组值的键/值?

// sample input
{
name: "Jackie",
age: 26,
friends: [ "David", "Ashley" ],
pets: [ "Rover" ],
birthday: "May 3",
family: [
{
name: "Lily",
relationship: "Mother"
},
{
name: "Richard",
relationship: "Father"
}
]
}
// expected output
{
name: "Jackie",
age: 26,
birthday: "May 3"
}

最佳答案

你对此的看法:

 Object.fromEntries(Object.entries(obj).filter( ([k,v]) => Object(v) !== v )) 

此过期将过滤掉每个具有对象值的键。当然,您可以根据需要自定义此过滤器

 Object.fromEntries(Object.entries(obj).filter( ([k,v]) => !Array.isArray(v) )) 

或者可能像@bramer 建议的那样,但是修改了原始 obj

for ( let k in obj )
if ( Array.isArray(obj[k]) delete obj[k]

可以包装以返回新的对象

function justPrimitive( obj, ret = {} ) 
for ( let k in obj )
if ( ! Array.isArray(obj[k]) ret[k] = obj[k]
return ret;
}

关于javascript - 如何仅从 json 根属性获取非数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61194123/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com