gpt4 book ai didi

javascript - JS : Looping through specific Object props and creating a new Object

转载 作者:行者123 更新时间:2023-12-03 08:35:11 24 4
gpt4 key购买 nike

我正在循环的对象有几个属性,例如:

contentAsset.custom = {
brandInfoHeader: 'header',
brandInfoLinkUrl: 'link1',
brandInfoLinkUrl2 : 'link2'
brandInfoLinkText: 'text1',
brandInfoLinkTextLink1 : 'text2' // and many more that I lose count
};

我想要所有 12 个具有键brandInfoTextLink 和brandInfoLinkUrl 的属性(每个属性6 个)。我有一个函数在 obj 上循环,但我不知道如何从具有不同编号的 props 海洋中获取这 12 个 props。我可以编写 12 个 if 语句,但这不是一个好的做法。功能:

function loopthru () {
var obj = {};

for (var key in contentAsset.custom){
obj[key] = contentAsset.custom[key];
}

return obj;
}

最佳答案

您可以使用正则表达式来查找所需的属性:

var contentAsset = {};
contentAsset.custom = {
brandInfoHeader: 'header',
brandInfoLinkUrl: 'link1',
brandInfoLinkUrl2: 'link2',
brandInfoLinkText: 'text1',
brandInfoLinkTextLink1: 'text2' // and many more that I lose count
};

function loopthru() {
var obj = {};

Object.keys(contentAsset.custom)
.filter(function (key) {
return /^brandInfoLink(Text|Url).*/.test(key);
})
.forEach(function(key) {
obj[key] = contentAsset.custom[key];
});

return obj;
}

snippet.log(JSON.stringify(loopthru()));
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

这是 Lodash 的版本:

var contentAsset = {};
contentAsset.custom = {
brandInfoHeader: 'header',
brandInfoLinkUrl: 'link1',
brandInfoLinkUrl2: 'link2',
brandInfoLinkText: 'text1',
brandInfoLinkTextLink1: 'text2' // and many more that I lose count
};

function loopthru() {
return _.pick(contentAsset.custom, function(val, key) {
return /^brandInfoLink(Text|Url).*/.test(key);
});
}

snippet.log(JSON.stringify(loopthru()));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

关于javascript - JS : Looping through specific Object props and creating a new Object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33236108/

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