You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中从数组对象中获取键值对

解决JSON对象数组的占位符替换问题

核心修改思路

  • 原代码针对单个对象编写,现在parameters是对象数组,需先从数组中提取目标对象(单元素数组取parameters[0],多元素数组则遍历数组)
  • 修正原有替换逻辑的缺陷:每次替换后需更新内容变量,避免重复基于原始模板替换,确保多占位符场景下能完成累积替换

场景1:数组仅含单个参数对象(你的示例情况)

var fs = require('fs');
var parameters = [
    {
      'Tenantid': 'a5462b57-a249-4778',
      "packagecategoryname":"Azure AD"
    }
];
var decodedContent = `export const msalConfig = {
    auth: {
      clientId: "%Tenantid%",
      authority: "https://login.microsoftonline.com/common",
      redirectUri: window.location.origin,
      postLogoutRedirectUri: window.location.origin,
    },
    cache: { cacheLocation: "localStorage", storeAuthStateInCookie: false }
};`

// 从数组中取出参数对象
const paramObj = parameters[0];
// 遍历键值对完成占位符替换
Object.entries(paramObj).forEach(([key, value]) => {
  const placeholder = `%${key}%`;
  if (decodedContent.includes(placeholder)) {
    decodedContent = decodedContent.replace(placeholder, value);
  }
});

// 打印最终替换后的内容
console.log(decodedContent);

场景2:数组包含多个参数对象(批量处理)

若API返回多组参数,需遍历数组生成对应内容:

var fs = require('fs');
var parameters = [
    {
      'Tenantid': 'a5462b57-a249-4778',
      "packagecategoryname":"Azure AD"
    },
    {
      'Tenantid': 'b89c3d2e-f1a0-4567',
      "packagecategoryname":"Microsoft 365"
    }
];
var templateContent = `export const msalConfig = {
    auth: {
      clientId: "%Tenantid%",
      authority: "https://login.microsoftonline.com/common",
      redirectUri: window.location.origin,
      postLogoutRedirectUri: window.location.origin,
    },
    cache: { cacheLocation: "localStorage", storeAuthStateInCookie: false }
};`

// 遍历数组生成所有替换后的内容
const results = parameters.map(paramObj => {
  let content = templateContent;
  Object.entries(paramObj).forEach(([key, value]) => {
    const placeholder = `%${key}%`;
    if (content.includes(placeholder)) {
      content = content.replace(placeholder, value);
    }
  });
  return content;
});

// 结果为替换后的内容数组
console.log(results);

额外说明

  • 保留了Object.entries()遍历键值对的原有逻辑,确保代码一致性
  • 修正了原模板字符串中的语法错误:cache对象末尾多余的分号已移除

内容的提问来源于stack exchange,提问作者Karan S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 08:35:23